Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Waiting on multiple threads to complete in Java

During the course of my program execution, a number of threads are started. The amount of threads varies depending on user defined settings, but they are all executing the same method with different variables.

In some situations, a clean up is required mid execution, part of this is stopping all the threads, I don't want them to stop immediately though, I just set a variable that they check for that terminates them. The problem is that it can be up to 1/2 second before the thread stops. However, I need to be sure that all threads have stopped before the clean up can continues. The cleanup is executed from another thread so technically I need this thread to wait for the other threads to finish.

I have thought of several ways of doing this, but they all seem to be overly complex. I was hoping there would be some method that can wait for a group of threads to complete. Does anything like this exist?

Thanks.

like image 646
A Jackson Avatar asked Sep 01 '09 07:09

A Jackson


People also ask

Does Java wait for all threads to finish?

Behind the scenes it is using default JVM's fork join pool which means that it will wait for all the threads to finish before continuing.

What is wait () and notify () in multithreading?

The wait() method causes the current thread to wait until another thread invokes the notify() or notifyAll() methods for that object. The notify() method wakes up a single thread that is waiting on that object's monitor. The notifyAll() method wakes up all threads that are waiting on that object's monitor.

What is purpose of wait () method in multithreading in Java?

The wait() method causes the current thread to wait indefinitely until another thread either invokes notify() for this object or notifyAll().


2 Answers

Just join them one by one:

for (Thread thread : threads) {   thread.join(); } 

(You'll need to do something with InterruptedException, and you may well want to provide a time-out in case things go wrong, but that's the basic idea...)

like image 162
Jon Skeet Avatar answered Oct 15 '22 14:10

Jon Skeet


If you are using java 1.5 or higher, you can try CyclicBarrier. You can pass the cleanup operation as its constructor parameter, and just call barrier.await() on all threads when there is a need for cleanup.

like image 36
Tadeusz Kopec for Ukraine Avatar answered Oct 15 '22 14:10

Tadeusz Kopec for Ukraine