使用ExecutorCompletionService.poll/take,您将在完成时收到Futures,按完成顺序(或多或少)。使用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 上找到完整代码。