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
精彩评论