IAm*_*aja 5 java concurrency future callable executorservice
我有以下代码哈希:
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?
}
}
Run Code Online (Sandbox Code Playgroud)
在for循环之后,我想等待所有工人完成,然后继续进行.什么是最好/最安全/最有效的方法?提前致谢!
countDownawait主线程,它将阻塞,直到工人完成.与使用执行程序服务上的方法相比,这是一种更通用的解决方案.
| 归档时间: |
|
| 查看次数: |
2567 次 |
| 最近记录: |