2

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?

Punter Vicky
  • 15,954
  • 56
  • 188
  • 315

5 Answers5

5

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.

Thomas Owens
  • 114,398
  • 98
  • 311
  • 431
3

for all threads do thread.join().

Alexei Kaigorodov
  • 13,189
  • 1
  • 21
  • 38
3

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.

KingCronus
  • 4,509
  • 1
  • 24
  • 49
2

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.

Helmuth M.
  • 541
  • 2
  • 11
2

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

bear foot
  • 105
  • 5