Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

wait until all threads finish their work in java

I'm writing an application that has 5 threads that get some information from web simultaneously and fill 5 different fields in a buffer class.
I need to validate buffer data and store it in a database when all threads finished their job.
How can I do this (get alerted when all threads finished their work) ?

like image 323
Ariyan Avatar asked Oct 29 '11 13:10

Ariyan


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.

Which method wait for a Java thread to finish?

The wait() and join() methods are used to pause the current thread. The wait() is used in with notify() and notifyAll() methods, but join() is used in Java to wait until one thread finishes its execution.

What does wait () do in Java?

wait() causes current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object. In other words, this method behaves exactly as if it simply performs the call wait(0).


1 Answers

The approach I take is to use an ExecutorService to manage pools of threads.

ExecutorService es = Executors.newCachedThreadPool(); for(int i=0;i<5;i++)     es.execute(new Runnable() { /*  your task */ }); es.shutdown(); boolean finished = es.awaitTermination(1, TimeUnit.MINUTES); // all tasks have finished or the time has been reached. 
like image 53
Peter Lawrey Avatar answered Oct 30 '22 05:10

Peter Lawrey