如何充分利用多核CPU,计算很大的List中所有整数的和(转)

  1. public class CountSumWithCallable {   
  2.   
  3.     /**  
  4.      * @param args  
  5.      * @throws InterruptedException   
  6.      * @throws ExecutionException   
  7.      */  
  8.     public static void main(String[] args) throws InterruptedException, ExecutionException {   
  9.         int threadCounts =19;//使用的线程数   
  10.         long sum=0;   
  11.         ExecutorService exec=Executors.newFixedThreadPool(threadCounts);   
  12.         List<Callable<Long>> callList=new ArrayList<Callable<Long>>();   
  13.         //生成很大的List   
  14.         List<Integer> list = new ArrayList<Integer>();   
  15.         for (int i = 0; i <= 1000000; i++) {   
  16.             list.add(i);   
  17.         }   
  18.         int len=list.size()/threadCounts;//平均分割List   
  19.         //List中的数量没有线程数多(很少存在)   
  20.         if(len==0){   
  21.             threadCounts=list.size();//采用一个线程处理List中的一个元素   
  22.             len=list.size()/threadCounts;//重新平均分割List   
  23.         }   
  24.         for(int i=0;i<threadCounts;i++){   
  25.             final List<Integer> subList;   
  26.             if(i==threadCounts-1){   
  27.                 subList=list.subList(i*len,list.size());   
  28.             }else{   
  29.                 subList=list.subList(i*len, len*(i+1)>list.size()?list.size():len*(i+1));   
  30.             }   
  31.             //采用匿名内部类实现   
  32.             callList.add(new Callable<Long>(){   
  33.                 public Long call() throws Exception {   
  34.                     long subSum=0L;   
  35.                     for(Integer i:subList){   
  36.                         subSum+=i;   
  37.                     }   
  38.                     System.out.println("分配给线程:"+Thread.currentThread().getName()+"那一部分List的整数和为:\tSubSum:"+subSum);   
  39.                     return subSum;   
  40.                 }   
  41.             });   
  42.         }   
  43.         List<Future<Long>> futureList=exec.invokeAll(callList);   
  44.         for(Future<Long> future:futureList){   
  45.             sum+=future.get();   
  46.         }   
  47.         exec.shutdown();   
  48.         System.out.println(sum);   
  49.     }   
  50.   
  51. }  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值