Van*_*ran 5 java multithreading thread-safety threadpool
我有一个类产生一堆线程,必须等到所有生成的线程完成.(我需要计算所有线程完成的时间).
MainClass生成所有线程,然后在它可以调用自己完成之前检查是否所有线程都已完成.
这个逻辑会起作用吗?如果是这样,有更好的方法吗?如果没有,我想更好地了解这种情况.
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();
}
}
}
Run Code Online (Sandbox Code Playgroud)
Tho*_*ler 11
notifyAll()比较慢.更好的方法是使用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();
Run Code Online (Sandbox Code Playgroud)