开发者

How to wait for all threads (variable number of threads) to finish to move on with Main?

I will make many开发者_JAVA百科 threads according to user input in a for loop. Therefore I won't be able to assign names for them. Is there a way to wait all of them to finish to move on with my main thread? I want them to be finished out of that for loop. I know I need to use a join but with many many threads, how will I use it? Or is there another way? It will be like this:

for(int i = 0; i<inputs.size(); i++)
  new SimpleThread(parameters).start();

go on with only main thread, others finished.

How can I do this?


Store the threads in a List<Thread>, then iterate the list and use thread.join()

You can also take a look at java.util.concurrent aids. CyclicBarrier or CountDownLatch (as indicated by others) for example.


Use a java.util.concurrent.CountDownLatch. Pass it along with parameters.

Also consider using a java.util.concurrent.Executors.newFixedThreadPool() to manage your thread life cycles (starting, stopping threads).


Create a countdown latch in the main thread, passed to the threads you spawn: http://download.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/CountDownLatch.html

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜