I have few threads that performs an actvity in parallel. I would have to proceed with the subsequent actvity only after all the threads are completed. Is there a way to achieve this?
-
Which thread should do the subsequent activity? Would it be ok if the last thread that finishes would do it? – thejh Apr 10 '12 at 12:49
-
possible duplicate of [Waiting on multiple threads to complete in Java](http://stackoverflow.com/questions/1361029/waiting-on-multiple-threads-to-complete-in-java) – thejh Apr 10 '12 at 12:50
-
Please use the search box to find an answer before you post. – thejh Apr 10 '12 at 12:51
-
Thanks - sure would do in future. – Punter Vicky Apr 11 '12 at 06:23
5 Answers
You should take a look at the join()
method in the Thread class. A join can be used to allow one thread to wait for another to complete. It's also overloaded to allow for the specification of a time to wait for the other thread to finish. Joins are discussed as part of the Java Tutorial on Concurrency.

- 114,398
- 98
- 311
- 431
http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Thread.html#join()
You can use Thread.join() in order to cause a wait until thread completion. Take a look at the Javadoc for more information.

- 4,509
- 1
- 24
- 49
I think using a http://docs.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/CountDownLatch.html is actually preferable over Thread.join() as it should scale better.

- 541
- 2
- 11
Conceptually, a way to address your problem is to create an observer object which will be referenced by every threads you are running. Once a thread is done it notifies the observer that it performed his task. Each time the Observer receive this kind of notification, it increment a counter, once the counter reach the number of threads, this means that all the threads are completed. then the Observer can start the final task.
That is for the theory. If you want there is a built-in java class for that: CountDownLatch

- 105
- 5