当我们通过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. bzoj4403: 序列统计

    我们很容易发现答案是C(R-L+N+1,N)-1 然后用一下lucas定理就行了 #include <iostream> #include <cstdio> #include ...

  2. IOS传值的几种方式

    1.代理 一对一 在第二个页面设置代理 1.1在最上方设置 //选择房间的代理 @protocol RoomVCDelegate <NSObject> 1.2设置代理方法 //方法 -(v ...

  3. tableView使用的易忘技术点(相对于自己)

    1.在tableView设置右向导航指示箭头 cell.accessoryType=UITableViewCellAccessoryDisclosureIndicator; 2.tableView的系 ...

  4. filter,map,reduce,lambda(python3)

    1.filter filter(function,sequence) 对sequence中的item依次执行function(item),将执行的结果为True(符合函数判断)的item组成一个lis ...

  5. shell处理mysql增、删、改、查

    引言     这几天做一个任务,比对两个数据表中的数据,昨天用PHP写了一个版本,但考虑到有的机器没有php或者php没有编译mysql扩展,就无法使用mysql系列的函数,脚本就无效了,今天写个sh ...

  6. English Snippets

    There is no Zen master to prod you with a stick, but I have some questions for you. Your answers wil ...

  7. Compiler Warning (level 3) C4800

    #pragma warning( disable : 4800 ) // forcing bool 'true' or 'false' ,忽略4800 警告#pragma warning( disab ...

  8. Linux 平台PostGIS安装

    1.前提条件: postgresql 9.6.1 已经通过源码方式安装完成并可成功运行. 2. other OS packets OS: CentOS 6.4 X64 X64: libxml2-dev ...

  9. 【原】使用webpack打包的后,公共请求路径的配置问题

    在我们公司,和后台接接口时,公共的请求路径我们是单独抽出来的,放在一个独立的public.js中,在public.js中存入那个公共变量 公共变量是这样 在其他地方使用ajax时,我们就这样使用 这种 ...

  10. jQuery关于隐式迭代的个人理解~

    1.JQuery对象" 如: $('div').text("div展示的信息") 可以看成"是一个包含一个dom数组 和 包含所有Jquery方法的容器 2.每 ...