I have a class which spawns a bunch of threads and have to wait till all the spawned threads are completed. ( I need to calculate the time for all threads to complete).
The MainClass spawns all the threads and then it checks whether all the threads are completed before it can call itself completed.
Will this logic work. If so, is there a better way to do this? If not , I would like to better understand this scenario.
class MainClass{
private boolean isCompleted;
...
for(task : tasks){
threadpool.execute(task);
}
for(task : tasks){
if(!task.isCompleted()){
task.wait()
}
}
isCompleted = true;
}
class Task{
public void run(){
....
....
synchronized(this){
task.completed = true;
notifyAll();
}
}
}
notifyAll()
is relatively slow. A better way is to use CountDownLatch
:
import java.util.concurrent.CountDownLatch;
int n = 10;
CountDownLatch doneSignal = new CountDownLatch(n);
// ... start threads ...
doneSignal.await();
// and within each thread:
doWork();
doneSignal.countDown();
There's no need for wait/notify in this case. You can just loop through the threads and call join()
. If the thread's already finished, the MainClass thread will just wait for the next one.
You might want to have a look at the higher-level utilities in the java.util.concurrent
package too.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With