15

正如问题标题本身所说,java中的Executors和ExecutorCompletionService类有什么区别?

我是线程新手,所以如果有人可以用一段代码来解释,那将有很大帮助。

4

2 回答 2

21

假设您有一组任务A, B, C, D, E,并且您希望在其中异步执行每个任务,并在Executor它们完成时一个接一个地处理结果。

使用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会首先完成。A因此,当主线程可能正在处理另一个任务(比如任务B)的结果时,主线程可能会空闲等待任务完成。结果处理延迟可以通过使用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 的实现包含一个结果队列。如果调用takepoll不调用以排空该队列,则会发生内存泄漏。有些人使用Future返回的submit来处理结果,这是不正确的用法。

于 2011-10-13T21:38:42.833 回答
3

AnExecutorCompletionService将简单地包装并委托给一个普通的Executor并提供方便的方法来检索最近完成的任务。

该 api 有几个例子可以帮助你前进

http://download.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/ExecutorCompletionService.html

于 2011-10-13T17:33:56.630 回答