栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

Java中的Executor和ExecutorCompletionservice之间的区别

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java中的Executor和ExecutorCompletionservice之间的区别

假设您有一组任务,

A, B, C, D, E
并且要在中异步执行每个任务,并在
Executor
完成时按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, Efor (Future<?> future:futures) {    ? result = future.get();    // Some processing here}

这种方法的问题是不能保证任务

A
将首先完成。因此,当主线程
A
可能正在处理另一个任务(例如task
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 orderfor (int i=0; i<futures.size(); i++) {    ? result = executorCompletionService.take().get();    // Some processing here}

因此,从本质上讲,

ExecutorCompletionService
当处理任务结果的顺序无关紧要时,可以用于提高效率。

需要注意的重要一件事。ExecutorCompletionService的实现包含一个结果队列。如果不调用

take
poll
耗尽该队列,将发生内存泄漏。某些人使用
Future
return
by
submit
处理结果,这不是正确的用法。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/470098.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号