gpt4 book ai didi

java - 如何在继续之前等待所有可调用对象完成执行?

转载 作者:行者123 更新时间:2023-12-04 16:45:53 27 4
gpt4 key购买 nike

我有以下代码散列:

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

最佳答案

您可以调用:

executor.shutdown();
executor.awaitTermination(Long.MAX_VALUE , TimeUnit.NANOSECONDS);

这将(几乎)无限期地等待任务完成。

关于java - 如何在继续之前等待所有可调用对象完成执行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16483233/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com