正如问题标题本身所说,Java 中的 Executors 和 ExecutorCompletionService 类有什么区别?
我是线程的新手,所以如果有人能用一段代码解释一下,那将有很大帮助。
最佳答案
假设您有一组任务 A、B、C、D、E
,并且您希望在 Executor
中异步执行每个任务并处理结果 1完成时增加 1。
使用 Executor
,您可以这样做:
List<Future<?>> futures = new ArrayList<Future<?>>();
futures.add(executorService.submit(A));
futures.add(executorService.submit(B));
futures.add(executorService.submit(C));
futures.add(executorService.submit(D));
futures.add(executorService.submit(E));
//This loop must process the tasks in the order they were submitted: A, B, C, D, E
for (Future<?> future:futures) {
? result = future.get();
// Some processing here
}
此方法的问题在于无法保证任务 A
将首先完成。因此,当主线程可以处理另一个任务(比如任务 B
)的结果时,它可能会空闲地阻塞等待任务 A
完成。使用 ExecutorCompletionService
可以减少结果处理延迟。
List<Future<?>> futures = new ArrayList<Future<?>>();
futures.add(executorCompletionService.submit(A));
futures.add(executorCompletionService.submit(B));
futures.add(executorCompletionService.submit(C));
futures.add(executorCompletionService.submit(D));
futures.add(executorCompletionService.submit(E));
//This for loop will process the tasks in the order they are completed,
//regardless of submission order
for (int i=0; i<futures.size(); i++) {
? result = executorCompletionService.take().get();
// Some processing here
}
因此,从本质上讲,ExecutorCompletionService
可用于在处理任务结果的顺序无关紧要时提高效率。
不过要注意一件重要的事情。 ExecutorCompletionService 的实现包含一个结果队列。如果未调用 take
或 poll
来清空该队列,则会发生内存泄漏。有些人使用 submit
返回的 Future
来处理结果,这是不正确的用法。
关于java - java中Executor和ExecutorCompletionservice的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7758020/