gpt4 book ai didi

java - ExecutorCompletionService 示例代码是否需要循环?

转载 作者:行者123 更新时间:2023-12-01 09:32:33 25 4
gpt4 key购买 nike

阅读JDK ExecutorCompletionService文档示例代码

/*
* Suppose instead that you would like to use the first non-null result
* of the set of tasks, ignoring any that encounter exceptions,
* and cancelling all other tasks when the first one is ready:
*
*
* void solve(Executor e,
* Collection<Callable<Result>> solvers)
* throws InterruptedException {
* CompletionService<Result> ecs
* = new ExecutorCompletionService<Result>(e);
* int n = solvers.size();
* List<Future<Result>> futures
* = new ArrayList<Future<Result>>(n);
* Result result = null;
* try {
* for (Callable<Result> s : solvers)
* futures.add(ecs.submit(s));
* for (int i = 0; i < n; ++i) { //??? what's the purpose for this loop?
* try {
* Result r = ecs.take().get();
* if (r != null) {
* result = r;
* break;
* }
* } catch (ExecutionException ignore) {}
* }
* }
* finally {
* for (Future<Result> f : futures)
* f.cancel(true);
* }
*
* if (result != null)
* use(result);
*/

我觉得这个loop不是必需的,因为take会一直阻塞,直到第一个Task成功,然后直接在那里爆发,我认为爆发时的i永远为零。

这是正确的吗?或者我错过了什么?

 *         for (int i = 0; i < n; ++i) { //??? what's the purpose for this loop? 
* try {
* Result r = ecs.take().get();
* if (r != null) {
* result = r;
* break;
* }
* } catch (ExecutionException ignore) {}
* }

最佳答案

在评论中这样说

* Suppose instead that you would like to use the first non-null result
* of the set of tasks, ignoring any that encounter exceptions,
* and cancelling all other tasks when the first one is ready:
*

如果第一个结果为空(任务已完成但结果为空),那么它将尝试获取下一个结果

如果当前尝试抛出 ExecutionException,则此 for 循环将跳转到下一个元素并尝试获取下一个结果

关于java - ExecutorCompletionService 示例代码是否需要循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39288442/

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