使用
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 {
Future<String> future;
do {
future = pool.isTerminated() ? service.poll() : service.take();
if (future != null) {
System.out.println(future.get());
}
} while (future != null);
} catch (ExecutionException | InterruptedException ex) { }
这将产生以下输出:
C:\dev\scrap>java CompletionExample
... after 500 ms ...
quick
... after 5 s ...
slow
请注意,这些时间是相对于程序启动而不是上一条消息的。
在Replit上测试一个工作示例。
invokeAll
返回的List<Future>
中开始迭代结果时,我可以在第一个完成之前阻塞,而在ExecutionCompletion
中,我会一直阻塞直到有任何一个结果可用?我的理解正确吗? - Cratylus