java中Executor和ExecutorCompletionservice之间的区别 [英] Difference between Executor and ExecutorCompletionservice in java
问题描述
正如问题标题本身所说的那样,Executors和ExecutorCompletionService类之间的区别是什么?
As the question title itself says what is the difference between Executors and ExecutorCompletionService classes in java?
我是Threading的新手,所以如果任何人可以用一段代码,这将有很大的帮助。
I am new to the Threading,so if any one can explain with a piece of code, that would help a lot.
推荐答案
假设你有一组任务 A ,B,C,D,E
并且您希望在 Executor
中异步执行它们,并在完成时逐个处理结果。
Suppose you had a set of tasks A, B, C, D, E
and you want to execute each of them asynchronously in an Executor
and process the results 1 by 1 as they complete.
使用执行者
,您可以这样做:
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
将首先完成。因此,主线程可能会阻塞空闲等待任务 A
完成,当它可以处理另一个任务的结果时(比如任务乙
)。使用 ExecutorCompletionService
可以减少结果处理延迟。
The problem with this method is that there is no guarantee that task A
will complete first. Thus, it is possible that the main thread will be blocking idly waiting for task A
to complete when it could be processing the result of another task (say task B
). Result processing latency could be reduced by using an 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
}
所以,实质上,<$当处理任务结果的顺序无关紧要时,可以使用c $ c> ExecutorCompletionService 来提高效率。
So, in essence, ExecutorCompletionService
could be used to squeeze out a little more efficiency when the order of processing task results does not matter.
一个重要的但要注意的事情。 ExecutorCompletionService的实现包含结果队列。如果没有调用 take
或 poll
来排空该队列,则会发生内存泄漏。有些人使用 submit
返回的 Future
来处理结果,这是不正确的用法。
One important thing to note though. The implementation of ExecutorCompletionService contains a queue of results. If take
or poll
are not called to drain that queue, a memory leak will occur. Some people use the Future
returned by submit
to process results and this is NOT correct usage.
这篇关于java中Executor和ExecutorCompletionservice之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!