当我们通过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. python初识生成器 迭代器

    生成器 带有 yield 的函数在 Python 中被称之为 generator(生成器) def xragns(): #定义函数生成器 print('小伙') yield ('好') #加上yiel ...

  2. 绘制图形与3D增强技巧(五)----多边形图元的使用及其他

    1.注意多边形图元中的多边形只能是平面的,而且必须为凸多边形,且多边形的边不能弯曲 2.细分和边界,可以人为设置边界边和非边界边 glEdgeFlag(true)//接下来所有点均为边界边起点 glE ...

  3. BZOJ 1109: [POI2007]堆积木Klo

    1109: [POI2007]堆积木Klo Time Limit: 10 Sec  Memory Limit: 162 MBSubmit: 948  Solved: 341[Submit][Statu ...

  4. Leetcode #2 Add two number

    Q: You are given two linked lists representing two non-negative numbers. The digits are stored in re ...

  5. Leetcode # 169, 229 Majority Element I and II

    Given an array of size n, find the majority element. The majority element is the element that appear ...

  6. http80端口转发(实现微信公众号接口绑定IP时,同时支持多个公众号)

    http80端口转发 背景 微信公众平台接口绑定服务器时,如果使用IP需要使用80端口,此组件可实现一个IP上绑定多个公众平台接口 使用方法 http://(IP)/WeixinMP/(转发的地址Ba ...

  7. poj1113 凸包

    result=对所有点凸包周长+pi*2*L WA了一次,被Pi的精度坑了 以后注意Pi尽可能搞精确一点.Pi=3.14还是不够用 Code: #include<vector> #incl ...

  8. C#关闭窗口代码

    if (MessageBox.Show("请您确认是否退出(Y/N)", "系统提示", MessageBoxButtons.YesNo, MessageBox ...

  9. Newton-Raphson算法简介及其R实现

    本文简要介绍了Newton-Raphson方法及其R语言实现并给出几道练习题供参考使用. 下载PDF格式文档(Academia.edu) Newton-Raphson Method Let $f(x) ...

  10. 用DOS命令打开IE浏览器、我的文档等等

    用DOS命令打开IE浏览器 在“start”-运行中直接输入网址就可以了.如输入百度: http://www.baidu.com Command:[ start  http://www.baidu.c ...