阅读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/