我刚在 这篇博文中找到了 CompletionService。但是,这并没有真正展示 CompletionService 相对于标准 ExecutorService 的优势。同样的代码可以用。那么,CompletionService 什么时候有用呢?
你能给出一个简短的代码示例,使其清晰明了吗?例如,此代码示例仅显示不需要 CompletionService 的地方(= 等效于 ExecutorService)
ExecutorService taskExecutor = Executors.newCachedThreadPool();
// CompletionService<Long> taskCompletionService =
// new ExecutorCompletionService<Long>(taskExecutor);
Callable<Long> callable = new Callable<Long>() {
@Override
public Long call() throws Exception {
return 1L;
}
};
Future<Long> future = // taskCompletionService.submit(callable);
taskExecutor.submit(callable);
while (!future.isDone()) {
// Do some work...
System.out.println("Working on something...");
}
try {
System.out.println(future.get());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}