如果我们使用 ExecutorCompletionService我们可以将一系列任务作为 Callable
提交,并将结果与 CompletionService
交互作为 queue
。
但也有 ExecutorService
的 invokeAll
接受一个 Collection
任务,我们得到一个 Future
列表code> 来检索结果。
据我所知,使用其中一个或另一个没有任何好处(除了我们使用 invokeAll
来避免 for
循环submit
任务到 CompletionService
),本质上它们是相同的想法,但略有不同。
那么为什么有两种不同的方式来提交一系列任务呢?我是否纠正了它们在性能方面是等效的?有没有一种情况比另一种更合适?我想不出一个。
最佳答案
使用 ExecutorCompletionService.poll/take
,您将在完成时收到 Future
,按完成顺序(或多或少)。使用ExecutorService.invokeAll
,你没有这个权力;您要么阻塞直到全部完成,要么指定一个超时,在此之后取消不完整的。
static class SleepingCallable implements Callable<String> {
final String name;
final long period;
SleepingCallable(final String name, final long period) {
this.name = name;
this.period = period;
}
public String call() {
try {
Thread.sleep(period);
} catch (InterruptedException ex) { }
return name;
}
}
现在,下面我将演示 invokeAll
的工作原理:
final ExecutorService pool = Executors.newFixedThreadPool(2);
final List<? extends Callable<String>> callables = Arrays.asList(
new SleepingCallable("quick", 500),
new SleepingCallable("slow", 5000));
try {
for (final Future<String> future : pool.invokeAll(callables)) {
System.out.println(future.get());
}
} catch (ExecutionException | InterruptedException ex) { }
pool.shutdown();
这会产生以下输出:
C:\dev\scrap>java CompletionExample
... after 5 s ...
quick
slow
使用 CompletionService
,我们会看到不同的输出:
final ExecutorService pool = Executors.newFixedThreadPool(2);
final CompletionService<String> service = new ExecutorCompletionService<String>(pool);
final List<? extends Callable<String>> callables = Arrays.asList(
new SleepingCallable("slow", 5000),
new SleepingCallable("quick", 500));
for (final Callable<String> callable : callables) {
service.submit(callable);
}
pool.shutdown();
try {
while (!pool.isTerminated()) {
final Future<String> future = service.take();
System.out.println(future.get());
}
} catch (ExecutionException | InterruptedException ex) { }
这会产生以下输出:
C:\dev\scrap>java CompletionExample
... after 500 ms ...
quick
... after 5 s ...
slow
注意时间是相对于程序开始的,而不是之前的消息。
您可以在 here 上找到完整代码.
关于java - 执行者完成服务?如果我们有invokeAll,为什么还需要一个?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11872520/