我刚刚在 this blog post 中找到了 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();
}
最佳答案
省略很多细节:
- ExecutorService = 传入队列 + 工作线程
- CompletionService = 传入队列 + 工作线程 + 输出队列
关于java - 什么时候应该使用 CompletionService 而不是 ExecutorService?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4912228/