【发布时间】:2013-05-05 04:41:36
【问题描述】:
我有以下代码散列出来:
public class MyCallable implements Callable<Long> {
@Override
public Long call() throws Exception {
// Do stuff...
}
}
public class MyController {
private ExecutorService executor = Executos.newCachedTreadPool();
public Long concurrentDoStuff() {
List<MyCallable> workers = makeWorkers();
List<Long> allResults = new ArrayList<Long>();
for(MyCallable worker : workers) {
Future<Long> workerResults = executor.submit(worker);
try {
allResults.add(workerResults.get());
} catch(InterruptedException ie) {
// Handle...
} catch(ExecutionException ee) {
// Handle...
}
}
// Question: how do I pause here and wait for all workers to finish?
}
}
在for-loop 之后,我想等待所有工作人员完成后再继续。最好/最安全/最有效的方法是什么?提前致谢!
【问题讨论】:
-
您想先提交所有工作,然后等待他们的结果。在您的代码中,您在汇总下一个作业之前等待每个结果,这会破坏并发性。
-
+1 @RalfH - 你应该保留一个期货列表,并且在你提交所有任务之前不要取消引用它们。
-
另外,您应该复制/粘贴您的代码。上面有错别字!
标签: java concurrency executorservice future callable