如果您控制线程的创建(提交给ExecutorService),那么您似乎可以使用
ExecutorCompletionService
看见
ExecutorCompletionService? Why do need one if we have invokeAll?
这里有各种各样的答案。
如果您不控制线程的创建,这里有一种方法,它允许您根据Ruby的启发“一个接一个地连接线程”(并知道哪个线程先完成,等等)。
ThreadWait
班级。
基本上,通过更新“监视线程”,当其他线程终止时会发出警报,您可以知道许多线程中的“下一个”线程何时终止。
你可以这样使用它:
JoinThreads join = new JoinThreads(threads);
for(int i = 0; i < threads.size(); i++) {
Thread justJoined = join.joinNextThread();
System.out.println("Done with a thread, just joined=" + justJoined);
}
来源:
public static class JoinThreads {
java.util.concurrent.LinkedBlockingQueue doneThreads =
new LinkedBlockingQueue();
public JoinThreads(List threads) {
for(Thread t : threads) {
final Thread joinThis = t;
new Thread(new Runnable() {
@Override
public void run() {
try {
joinThis.join();
doneThreads.add(joinThis);
}
catch (InterruptedException e) {
// "should" never get here, since we control this thread and don't call interrupt on it
}
}
}).start();
}
}
Thread joinNextThread() throws InterruptedException {
return doneThreads.take();
}
}
好的部分是它与通用Java线程一起工作,没有修改,任何线程都可以被连接。需要注意的是,它需要一些额外的线程创建。另外,如果您不调用joinNextThread()的完整次数,并且没有“close”方法等,那么这个特定的实现将“留下线程”。如果您希望创建一个更完善的版本,请在此处注释。您也可以将这种类型的模式用于“未来”而不是线程对象等。