2

I will make many 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?

Michael Myers
  • 188,989
  • 46
  • 291
  • 292
Ada
  • 624
  • 3
  • 17
  • 31
  • You may want to consider using one work thread and adding [SwingWorker](http://download.oracle.com/javase/tutorial/uiswing/concurrency/worker.html)s to it – Brad Mace Dec 23 '10 at 23:01
  • possible duplicate of [How to wait for a set of threads to complete?](http://stackoverflow.com/questions/1252190/how-to-wait-for-a-set-of-threads-to-complete) – hugomg Nov 25 '11 at 20:16

3 Answers3

7

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.

Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140
5

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).

bluish
  • 26,356
  • 27
  • 122
  • 180
Spike Gronim
  • 6,154
  • 22
  • 21
2

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

James
  • 8,512
  • 1
  • 26
  • 28