假如有Thread1、Thread2、ThreaD3、Thread4四条线程分别统计C、D、E、F四个盘的大小,所有线程都统计完毕交给Thread5线程去做汇总,应当如何实现?

 一般情况,我们实现多线程都是Thread或者Runnable(后者比较多),但是,这两种都是没返回值的,所以我们需要使用callable(有返回值的多线程)和future(获得线程的返回值)来实现了。


[java]  view plain  copy
  1. /** 
  2.  * 假如有Thread1、Thread2、ThreaD3、Thread4四条线程分别统计C、D、E、F四个盘的大小,所有线程都统计完毕交给Thread5线程去做汇总,应当如何实现? 
  3.  */  
  4. public class TestThread {  
  5.     public static void main(String[] args) {  
  6.         ThreadCount tc = null;  
  7.         ExecutorService es = Executors.newCachedThreadPool();//线程池  
  8.         CompletionService<Integer> cs = new ExecutorCompletionService<Integer>(es);  
  9.         for(int i=0;i<4;i++){  
  10.             tc = new ThreadCount(i+1);  
  11.             cs.submit(tc);  
  12.         }  
  13.           
  14.         // 添加结束,及时shutdown,不然主线程不会结束  
  15.         es.shutdown();  
  16.           
  17.         int total = 0;  
  18.         for(int i=0;i<4;i++){  
  19.             try {  
  20.                 total+=cs.take().get();  
  21.             } catch (InterruptedException e) {  
  22.                 e.printStackTrace();  
  23.             } catch (ExecutionException e) {  
  24.                 e.printStackTrace();  
  25.             }  
  26.         }  
  27.           
  28.         System.out.println(total);  
  29.     }  
  30. }  
  31.   
  32. class ThreadCount implements Callable<Integer>{  
  33.     private int type;  
  34.     ThreadCount(int type){  
  35.         this.type = type;  
  36.     }  
  37.     @Override  
  38.     public Integer call() throws Exception {  
  39.         if(type==1){  
  40.             System.out.println("C盘统计大小");  
  41.             return 1;  
  42.         }else if(type==2){  
  43.             Thread.sleep(20000);  
  44.             System.out.println("D盘统计大小");  
  45.             return 2;  
  46.         }else if(type==3){  
  47.             System.out.println("E盘统计大小");  
  48.             return 3;  
  49.         }else if(type==4){  
  50.             System.out.println("F盘统计大小");  
  51.             return 4;  
  52.         }  
  53.         return null;  
  54.     }  
  55. }  


ps:一个需要注意的小细节,cs.take.get()获取返回值,是按照完成的顺序的,即上面案例返回顺序是CEFD

更多详细相关,请戳我

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值