繁体   English   中英

java中Executor和ExecutorCompletionservice的区别

[英]Difference between Executor and ExecutorCompletionservice in java

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

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

假设您有一组任务A, B, C, D, E并且您希望在Executor异步执行它们中的每一个,并在它们完成时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会先完成。 因此,当主线程可能正在处理另一个任务(比如任务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 的实现包含一个结果队列。 如果没有调用takepoll来排空该队列,则会发生内存泄漏。 有些人使用submit返回的Future来处理结果,这不是正确的用法。

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

该 api 有一些示例可以帮助您入门

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM