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 useCountDownLatch: