Reputation: 5834
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();
}
}
}
Upvotes: 5
Views: 1414
Reputation: 7866
All this can be done by java.util.concurrent.ExecutorService.
class MainClass {
...
ExecutorService executor = Executors.newCachedThreadPool();
List<Callable> tasks = ...; // prepare your tasks
// this invokes all tasks in parallel and waits until all are done
executor.invokeAll(tasks);
...
}
That's about it.
Upvotes: 4
Reputation: 32407
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.
Upvotes: 4
Reputation: 50097
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();
Upvotes: 11