当我们通过Executor提交一组并发执行的任务,并且希望在每一个任务完成后能立即得到结果,有两种方式可以采取:

方式一:

通过一个list来保存一组future,然后在循环中轮训这组future,直到每个future都已完成。如果我们不希望出现因为排在前面的任务阻塞导致后面先完成的任务的结果没有及时获取的情况,那么在调用get方式时,需要将超时时间设置为0

  1. public class CompletionServiceTest {
  2. static class Task implements Callable<String>{
  3. private int i;
  4. public Task(int i){
  5. this.i = i;
  6. }
  7. @Override
  8. public String call() throws Exception {
  9. Thread.sleep(10000);
  10. return Thread.currentThread().getName() + "执行完任务:" + i;
  11. }
  12. }
  13. public static void main(String[] args){
  14. testUseFuture();
  15. }
  16. private static void testUseFuture(){
  17. int numThread = 5;
  18. ExecutorService executor = Executors.newFixedThreadPool(numThread);
  19. List<Future<String>> futureList = new ArrayList<Future<String>>();
  20. for(int i = 0;i<numThread;i++ ){
  21. Future<String> future = executor.submit(new CompletionServiceTest.Task(i));
  22. futureList.add(future);
  23. }
  24. while(numThread > 0){
  25. for(Future<String> future : futureList){
  26. String result = null;
  27. try {
  28. result = future.get(0, TimeUnit.SECONDS);
  29. } catch (InterruptedException e) {
  30. e.printStackTrace();
  31. } catch (ExecutionException e) {
  32. e.printStackTrace();
  33. } catch (TimeoutException e) {
  34. //超时异常直接忽略
  35. }
  36. if(null != result){
  37. futureList.remove(future);
  38. numThread--;
  39. System.out.println(result);
  40. //此处必须break,否则会抛出并发修改异常。(也可以通过将futureList声明为CopyOnWriteArrayList类型解决)
  41. break;
  42. }
  43. }
  44. }
  45. }
  46. }

方式二:

第一种方式显得比较繁琐,通过使用ExecutorCompletionService,则可以达到代码最简化的效果。

  1. public class CompletionServiceTest {
  2. static class Task implements Callable<String>{
  3. private int i;
  4. public Task(int i){
  5. this.i = i;
  6. }
  7. @Override
  8. public String call() throws Exception {
  9. Thread.sleep(10000);
  10. return Thread.currentThread().getName() + "执行完任务:" + i;
  11. }
  12. }
  13. public static void main(String[] args) throws InterruptedException, ExecutionException{
  14. testExecutorCompletionService();
  15. }
  16. private static void testExecutorCompletionService() throws InterruptedException, ExecutionException{
  17. int numThread = 5;
  18. ExecutorService executor = Executors.newFixedThreadPool(numThread);
  19. CompletionService<String> completionService = new ExecutorCompletionService<String>(executor);
  20. for(int i = 0;i<numThread;i++ ){
  21. completionService.submit(new CompletionServiceTest.Task(i));
  22. }
  23. }
  24. for(int i = 0;i<numThread;i++ ){
  25. System.out.println(completionService.take().get());
  26. }
  27. }

ExecutorCompletionService分析:

CompletionService是Executor和BlockingQueue的结合体。

  1. public ExecutorCompletionService(Executor executor) {
  2. if (executor == null)
  3. throw new NullPointerException();
  4. this.executor = executor;
  5. this.aes = (executor instanceof AbstractExecutorService) ?
  6. (AbstractExecutorService) executor : null;
  7. this.completionQueue = new LinkedBlockingQueue<Future<V>>();
  8. }

任务的提交和执行都是委托给Executor来完成。当提交某个任务时,该任务首先将被包装为一个QueueingFuture,

  1. public Future<V> submit(Callable<V> task) {
  2. if (task == null) throw new NullPointerException();
  3. RunnableFuture<V> f = newTaskFor(task);
  4. executor.execute(new QueueingFuture(f));
  5. return f;
  6. }

QueueingFuture是FutureTask的一个子类,通过改写该子类的done方法,可以实现当任务完成时,将结果放入到BlockingQueue中。

  1. private class QueueingFuture extends FutureTask<Void> {
  2. QueueingFuture(RunnableFuture<V> task) {
  3. super(task, null);
  4. this.task = task;
  5. }
  6. protected void done() { completionQueue.add(task); }
  7. private final Future<V> task;
  8. }

而通过使用BlockingQueue的take或poll方法,则可以得到结果。在BlockingQueue不存在元素时,这两个操作会阻塞,一旦有结果加入,则立即返回。

  1. public Future<V> take() throws InterruptedException {
  2. return completionQueue.take();
  3. }
  4. public Future<V> poll() {
  5. return completionQueue.poll();
  6. }
  7. 原文:http://xw-z1985.iteye.com/blog/1997077

获取Executor提交的并发执行的任务返回结果的两种方式/ExecutorCompletionService使用的更多相关文章

  1. Java并发编程:线程间协作的两种方式:wait、notify、notifyAll和Condition

    Java并发编程:线程间协作的两种方式:wait.notify.notifyAll和Condition 在前面我们将了很多关于同步的问题,然而在现实中,需要线程之间的协作.比如说最经典的生产者-消费者 ...

  2. 19、Java并发编程:线程间协作的两种方式:wait、notify、notifyAll和Condition

    Java并发编程:线程间协作的两种方式:wait.notify.notifyAll和Condition 在前面我们将了很多关于同步的问题,然而在现实中,需要线程之间的协作.比如说最经典的生产者-消费者 ...

  3. 并发编程 - 进程 - 1.开启子进程的两种方式/2.查看pid/3.Process对象的其他属性或方法/4.守护进程

    1.开启子进程的两种方式: # 方式1: from multiprocessing import Process import time def task(name): print('%s is ru ...

  4. 并发编程 - 线程 - 1.开启线程的两种方式/2.进程与线程的区别/3.Thread对象的其他属性或方法/4.守护线程

    1.开启线程的两种方式: 进程,线程: 进程只是用来把资源集中到一起(进程只是一个资源单位,或者说资源集合)而线程才是cpu上的执行单位) 1.同一个进程内的多个线程共享该进程内的地址资源 2.创建线 ...

  5. 获取表单选中的值(利用php和js两种方式)

    php代码中获取表单中单选按钮的值: (单选按钮只能让我们选择一个,这里有一个“checked”属性,这是用来默认选取的,我们每次刷新我们的页面时就默认为这个值.) 例: <form name= ...

  6. JavaWeb学习总结(十五)Jsp中提交的表单的get和post的两种方式

    两者的比较: Get方式: 将请求的参数名和值转换成字符串,并附加在原来的URL之后,不安全 传输的数据量较小,一般不能大于2KB: post方式: 数量较大: 请求的参数和值放在HTML的请求头中, ...

  7. 获取select文本框的下拉菜单文字内容的两种方式

    <body> <div class="box"> <select id="sel"> <option value=&q ...

  8. 【linux】linux 下 shell命令 执行结果赋值给变量【两种方式】

    方法1:[通用方法] 使用Tab键上面的反引号 例子如下: find命令 模糊查询在/apps/swapping目录下 查找 文件名中包含swapping并且以.jar结尾的文件 使用反引号 引住命令 ...

  9. python执行系统命令后获取返回值的几种方式集合

    python执行系统命令后获取返回值的几种方式集合 今天小编就为大家分享一篇python执行系统命令后获取返回值的几种方式集合,具有很好的参考价值,希望对大家有所帮助.一起跟随小编过来看看吧 第一种情 ...

随机推荐

  1. 【POJ 2826】An Easy Problem?!(几何、线段)

    两个木条装雨水能装多少. 两线段相交,且不遮盖的情况下才可能装到水. 求出交点,再取两线段的较高端点的较小值h,(h-交点的y)为三角形的高. 三角形的宽即为(h带入两条线段所在直线得到的横坐标的差值 ...

  2. 高级语言虚拟机的一点理解,对比.NET和Java平台

    最近学习了一些高级语言虚拟机的知识,在此对.NET平台和java平台做一个简单的比较.对java平台已经很熟了,所以此处只介绍.NET平台下的一些概念. 一.CLI 通用语言基础架构(Common L ...

  3. 【BZOJ-4688】One-Dimensional 矩阵乘法

    4688: One-Dimensional Time Limit: 30 Sec  Memory Limit: 256 MBSubmit: 19  Solved: 12[Submit][Status] ...

  4. 【BZOJ-4059】Non-boring sequences 线段树 + 扫描线 (正解暴力)

    4059: [Cerc2012]Non-boring sequences Time Limit: 10 Sec  Memory Limit: 128 MBSubmit: 440  Solved: 16 ...

  5. 【bzoj2118】 墨墨的等式

    http://www.lydsy.com/JudgeOnline/problem.php?id=2118 (题目链接) 题意 给出${B}$的取值范围${[Bmin,Bmax]}$,求方程${a_{1 ...

  6. mvc remote的验证

    1,问题 在mvc验证的时候怎么自定义验证action?比如说验证用户名是否重复. 2.解决方法 通过remote 的特性 第一参数是对应的action 第二个对应的是controller contr ...

  7. Mono开发环境搭建(Windows)

    一.下载 1.登录http://www.mono-project.com/下载 2.开发工具Xamarin Studio(好像是免费) http://www.monodevelop.com/downl ...

  8. Birthday-24

    2013 LEXUS花样滑冰 和母亲在一起,生日快乐!

  9. 文件内容统计——Linux wc命令

    有了该命令,就可以得到当前目录下所有符合条件的文件总数,如下: find -type f | wc -l 这个命令的功能也很好记,因为它功能很有限: wc -c filename:显示一个文件的字节数 ...

  10. C#用正则表达式对IP进行排序

    static void Main(string[] args) { string IPs = " 192.168.1.1 202.47.4.6 1.2.3.3 "; Console ...