转载请标明出处:http://blog.csdn.net/lmj623565791/article/details/27250059

一般情况下,我们使用Runnable作为基本的任务表示形式,但是Runnable是一种有很大局限的抽象,run方法中只能记录日志,打印,或者把数据汇总入某个容器(一方面内存消耗大,另一方面需要控制同步,效率很大的限制),总之不能返回执行的结果;比如同时1000个任务去网络上抓取数据,然后将抓取到的数据进行处理(处理方式不定),我觉得最好的方式就是提供回调接口,把处理的方式最为回调传进去;但是现在我们有了更好的方式实现:CompletionService + Callable

Callable的call方法可以返回执行的结果;

CompletionService将Executor(线程池)和BlockingQueue(阻塞队列)结合在一起,同时使用Callable作为任务的基本单元,整个过程就是生产者不断把Callable任务放入阻塞对了,Executor作为消费者不断把任务取出来执行,并返回结果;

优势:

a、阻塞队列防止了内存中排队等待的任务过多,造成内存溢出(毕竟一般生产者速度比较快,比如爬虫准备好网址和规则,就去执行了,执行起来(消费者)还是比较慢的)

b、CompletionService可以实现,哪个任务先执行完成就返回,而不是按顺序返回,这样可以极大的提升效率;

1、CompletionService : Executor + BlockingQueue 

下面看个例子:

 

[java]  view plain copy Java并发专题 带返回结果的批量任务执行 Java并发专题 带返回结果的批量任务执行
 
  1. package com.zhy.concurrency.completionService;  
  2.   
  3. import java.util.Random;  
  4. import java.util.concurrent.BlockingQueue;  
  5. import java.util.concurrent.Callable;  
  6. import java.util.concurrent.CompletionService;  
  7. import java.util.concurrent.ExecutionException;  
  8. import java.util.concurrent.ExecutorCompletionService;  
  9. import java.util.concurrent.ExecutorService;  
  10. import java.util.concurrent.Executors;  
  11. import java.util.concurrent.Future;  
  12. import java.util.concurrent.LinkedBlockingDeque;  
  13.   
  14. /** 
  15.  * 将Executor和BlockingQueue功能融合在一起,可以将Callable的任务提交给它来执行, 然后使用take()方法获得已经完成的结果 
  16.  *  
  17.  * @author zhy 
  18.  *  
  19.  */  
  20. public class CompletionServiceDemo  
  21. {  
  22.   
  23.     public static void main(String[] args) throws InterruptedException,  
  24.             ExecutionException  
  25.     {  
  26.         /** 
  27.          * 内部维护11个线程的线程池 
  28.          */  
  29.         ExecutorService exec = Executors.newFixedThreadPool(11);  
  30.         /** 
  31.          * 容量为10的阻塞队列 
  32.          */  
  33.         final BlockingQueue<Future<Integer>> queue = new LinkedBlockingDeque<Future<Integer>>(  
  34.                 10);  
  35.         //实例化CompletionService  
  36.         final CompletionService<Integer> completionService = new ExecutorCompletionService<Integer>(  
  37.                 exec, queue);  
  38.   
  39.         /** 
  40.          * 模拟瞬间产生10个任务,且每个任务执行时间不一致 
  41.          */  
  42.         for (int i = 0; i < 10; i++)  
  43.         {  
  44.             completionService.submit(new Callable<Integer>()  
  45.             {  
  46.                 @Override  
  47.                 public Integer call() throws Exception  
  48.                 {  
  49.                     int ran = new Random().nextInt(1000);  
  50.                     Thread.sleep(ran);  
  51.                     System.out.println(Thread.currentThread().getName()  
  52.                             + " 休息了 " + ran);  
  53.                     return ran;  
  54.                 }  
  55.             });  
  56.         }  
  57.           
  58.         /** 
  59.          * 立即输出结果 
  60.          */  
  61.         for (int i = 0; i < 10; i++)  
  62.         {  
  63.             try  
  64.             {     
  65.                 //谁最先执行完成,直接返回  
  66.                 Future<Integer> f = completionService.take();  
  67.                 System.out.println(f.get());  
  68.             } catch (InterruptedException e)  
  69.             {  
  70.                 e.printStackTrace();  
  71.             } catch (ExecutionException e)  
  72.             {  
  73.                 e.printStackTrace();  
  74.             }  
  75.         }  
  76.   
  77.         exec.shutdown();  
  78.   
  79.     }  
  80.   
  81. }  

输出结果:

 

 

[java]  view plain copy Java并发专题 带返回结果的批量任务执行 Java并发专题 带返回结果的批量任务执行
 
  1. pool-1-thread-4 休息了 52  
  2. 52  
  3. pool-1-thread-1 休息了 59  
  4. 59  
  5. pool-1-thread-10 休息了 215  
  6. 215  
  7. pool-1-thread-9 休息了 352  
  8. 352  
  9. pool-1-thread-5 休息了 389  
  10. 389  
  11. pool-1-thread-3 休息了 589  
  12. 589  
  13. pool-1-thread-2 休息了 794  
  14. 794  
  15. pool-1-thread-7 休息了 805  
  16. 805  
  17. pool-1-thread-6 休息了 909  
  18. 909  
  19. pool-1-thread-8 休息了 987  
  20. 987  


最先执行完成的直接返回,并不需要按任务提交的顺序执行,如果需要写个高并发的程序,且每个任务需要返回执行结果,这是个相当不错的选择!

 

 

2、ExecutorService.invokeAll

ExecutorService的invokeAll方法也能批量执行任务,并批量返回结果,但是呢,有个我觉得很致命的缺点,必须等待所有的任务执行完成后统一返回,一方面内存持有的时间长;另一方面响应性也有一定的影响,毕竟大家都喜欢看看刷刷的执行结果输出,而不是苦苦的等待;

下面看个例子:

 

[java]  view plain copy Java并发专题 带返回结果的批量任务执行 Java并发专题 带返回结果的批量任务执行
 
  1. package com.zhy.concurrency.executors;  
  2.   
  3. import java.util.ArrayList;  
  4. import java.util.List;  
  5. import java.util.Random;  
  6. import java.util.concurrent.Callable;  
  7. import java.util.concurrent.ExecutionException;  
  8. import java.util.concurrent.ExecutorService;  
  9. import java.util.concurrent.Executors;  
  10. import java.util.concurrent.Future;  
  11.   
  12. public class TestInvokeAll  
  13. {  
  14.   
  15.     public static void main(String[] args) throws InterruptedException,  
  16.             ExecutionException  
  17.     {  
  18.         ExecutorService exec = Executors.newFixedThreadPool(10);  
  19.   
  20.         List<Callable<Integer>> tasks = new ArrayList<Callable<Integer>>();  
  21.         Callable<Integer> task = null;  
  22.         for (int i = 0; i < 10; i++)  
  23.         {  
  24.             task = new Callable<Integer>()  
  25.             {  
  26.                 @Override  
  27.                 public Integer call() throws Exception  
  28.                 {  
  29.                     int ran = new Random().nextInt(1000);  
  30.                     Thread.sleep(ran);  
  31.                     System.out.println(Thread.currentThread().getName()+" 休息了 " + ran );  
  32.                     return ran;  
  33.                 }  
  34.             };  
  35.   
  36.             tasks.add(task);  
  37.         }  
  38.           
  39.         long s = System.currentTimeMillis();  
  40.           
  41.           
  42.         List<Future<Integer>> results = exec.invokeAll(tasks);  
  43.           
  44.         System.out.println("执行任务消耗了 :" + (System.currentTimeMillis() - s) +"毫秒");  
  45.           
  46.         for (int i = 0; i < results.size(); i++)  
  47.         {  
  48.             try  
  49.             {  
  50.                 System.out.println(results.get(i).get());  
  51.             } catch (Exception e)  
  52.             {  
  53.                 e.printStackTrace();  
  54.             }  
  55.         }  
  56.   
  57.           
  58.         exec.shutdown();  
  59.   
  60.     }  
  61.   
  62. }  


执行结果:

 

 

[java]  view plain copy Java并发专题 带返回结果的批量任务执行 Java并发专题 带返回结果的批量任务执行
 
  1. pool-1-thread-10 休息了 1  
  2. pool-1-thread-5 休息了 59  
  3. pool-1-thread-6 休息了 128  
  4. pool-1-thread-1 休息了 146  
  5. pool-1-thread-3 休息了 158  
  6. pool-1-thread-7 休息了 387  
  7. pool-1-thread-9 休息了 486  
  8. pool-1-thread-8 休息了 606  
  9. pool-1-thread-4 休息了 707  
  10. pool-1-thread-2 休息了 817  
  11. 执行任务消耗了 :819毫秒  
  12. 146  
  13. 817  
  14. 158  
  15. 707  
  16. 59  
  17. 128  
  18. 387  
  19. 606  
  20. 486  
  21. 1  


我特意在任务提交完成打印了一个时间,然后invokeAll执行完成后打印了下时间,可以看出invokeAll返回是等待所有线程执行完毕的。这点来说,我觉得可用性不如CompletionService。

 

 

嗯,对于批量执行任务,且携带返回结果的案例就到这里~如果有疑问或者代码中存在错误请指出~

分类:

技术点:

相关文章: