我有以下代码散列:
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
循环之后,我想等待所有工作人员完成后再继续。最好/最安全/最有效的方法是什么?提前致谢!