我有一个类,它派生了一堆线程,必须等到所有派生的线程都完成。(我需要计算所有线程完成的时间)。
MainClass生成所有线程,然后在调用自己complete之前检查是否所有线程都已完成。
这个逻辑行得通吗。如果是这样,有更好的方法吗?如果没有,我想更好地理解这种情况。
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()
相对较慢。更好的方法是使用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();
在这种情况下不需要等待/通知。您可以在线程中循环并调用join()
。如果线程已经完成,MainClass线程将只等待下一个线程。
您可能还想看看java.util.concurrent
包中的高级实用程序。
所有这些都可以通过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);
...
}
仅此而已。