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

方式一:

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

Java代码  
  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,则可以达到代码最简化的效果。

Java代码  
  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的结合体。

Java代码  
  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,

Java代码  
  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中。

Java代码  
  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不存在元素时,这两个操作会阻塞,一旦有结果加入,则立即返回。

Java代码  
  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

转载于:https://www.cnblogs.com/langtianya/p/5013353.html

获取Executor提交的并发执行的任务返回结果的两种方式/ExecutorCompletionService使用...相关推荐

  1. python 并发执行命令_python: 多线程实现的两种方式及让多条命令并发执行

    一 概念介绍 Thread 是threading模块中最重要的类之一,可以使用它来创建线程.有两种方式来创建线程:一种是通过继承Thread类,重写它的run方法:另一种是创建一个threading. ...

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

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

  3. 获取距离某坐标附近一定范围内的点的两种方式

    获取距离某坐标附近一定范围内的点的两种方式 场景:数据库中有一些点坐标,需要查找出距离当前位置2千米范围内的坐标 方式1:根据两个经纬度计算距离,Oracle/MySql计算地表两点之间的距离: Or ...

  4. linux中安shell怎么传入参数,【linux】linux 下 shell命令 执行结果赋值给变量【两种方式】...

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

  5. C++ string获取文件路径文件名、文件路径、文件后缀(两种方式)

    windows路径有两种方式,一种正斜杠,一种反斜杠都可以表示路径,该方法可以支持这两种表达方法 方法一:采用substr()进行分割 string path1 = "D:/datas/Fu ...

  6. 【大数据开发】SparkCore——Spark作业执行流程、RDD编程的两种方式、简单算子

    文章目录 一.Spark作业执行流程(重点) 二.RDD编程 2.1创建RDD的⼆种⽅式: 2.2Transformation算⼦ 2.3Action算子 三.简单算子(必须掌握) 3.1 map.m ...

  7. Python day 34 并发编程、PID/PPID、实现多进程得两种方式

    ## 进程及并发的产生 ```python 进程指的是正在运行的程序,是一系列过程的统称,也是操作系统在调度和进行资源分配的基本单位 并发,指的是多个任务同时被执行,并发编程指的是编写支持多任务并发的 ...

  8. python: 多线程实现的两种方式及让多条命令并发执行

    一 概念介绍 Thread 是threading模块中最重要的类之一,可以使用它来创建线程.有两种方式来创建线程:一种是通过继承Thread类,重写它的run方法:另一种是创建一个threading. ...

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

    第一种情况 os.system('ps aux') 执行系统命令,没有返回值 第二种情况 result = os.popen('ps aux') res = result.read() for lin ...

最新文章

  1. linux centos6 安装 crontab
  2. Py之demjson:Python库之demjson的简介、安装、使用方法详细攻略
  3. 在statspack显示完整的SQL
  4. Azure App Service 如何在第一时间用上最新版 .NET Core
  5. 别再面向 for 循环编程了,JDK 自带的观察者模式就很香!
  6. 给button加href
  7. Apache 工作模式配置优化
  8. Oracle的锁表与解锁
  9. Servlet容器原型(三)——Tomcat 4默认连接器浅谈
  10. 化学人学python有前途吗-转载:python之蟒开启理论计算化学的新时代
  11. scratch python的区别ev3_机器人编程和少儿编程,傻傻分不清—乐高EV3入门感想
  12. WinMTR使用教程(附图)
  13. 照片怎么转PDF格式?这两个方法快来学习下
  14. 51单片机c语言数组怎么用,51单片机之C语言-4.2数组
  15. 苹果gamecenter未能连接服务器,win7系统GameCenter无法连接服务器的解决方法
  16. oa系统需要的服务器配置,oa办公系统需要服务器配置
  17. 苏州大学计算机学院导师洪宇介绍,苏州大学计算机科学与技术学院硕导介绍:马小虎...
  18. qlineedit 获取文本_Python如何获取QLineEdit文本?
  19. 序列(sequence)(Python入门十二)
  20. 反编译jad的命令使用

热门文章

  1. 【堆栈】最近有兴趣的几个问题
  2. GideView 动态列模板
  3. [翻译]使用C#创建SQL Server的存储过程(Visual Studio 2005 + SQL Server 2005)
  4. html粘贴excel内容,如何用JS解析剪切板里的excel内容
  5. 作业——Windows核心编程学习手札系列之五
  6. linux中ramdisk的使用
  7. python的数值类型和运算符_python的数值类型和运算符
  8. python中迭代器的实现原理_Python 进阶应用教程
  9. td里面的内容加了br不起作用_刀圈TD黑暗游侠,最容易打金之一!!
  10. 约瑟夫环的问题--剑指 Offer 62. 圆圈中最后剩下的数字