微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

并发处理巨量的List适用快速批量处理巨量数据 2


import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;


public class LargSumWithCallable {
	
	static int threadCounts =10;//使用的线程数  
	static long sum=0; 
    
  public static void main(String []args) throws InterruptedException,ExecutionException{
	
	     
     
    ExecutorService exec=Executors.newFixedThreadPool(threadCounts);  
    List<Callable<Long>> callList=new ArrayList<Callable<Long>>();  
 
    List<Integer> list = new ArrayList<Integer>();
    
    for (int j = 0; j <= 1000000;j++)  {  
        list.add(j);  
    }
     
    int len=list.size()/threadCounts;//平均分割List  
    //List中的数量没有线程数多(很少存在)  
    if(len==0){  
        threadCounts=list.size();//采用一个线程处理List中的一个元素  
        len=list.size()/threadCounts;//重新平均分割List  
    }  
    for(int i=0;i<threadCounts;i++){  
        final List<Integer> subList;  
        if(i==threadCounts-1){  
            subList=list.subList(i*len,list.size());  
        }else{  
            subList=list.subList(i*len,len*(i+1)>list.size()?list.size():len*(i+1));  
        }  
        //采用匿名内部类实现  
        callList.add(new Callable<Long>(){  
            public Long call() throws Exception {  
                long subSum=0L;  
                for(Integer i:subList){  
                    subSum+=i;  
                }  
                System.out.println("分配给线程:"+Thread.currentThread().getName()+"那一部分List的整数和为:\tSubSum:"+subSum);  
                return subSum;  
            }  
        });  
    }  
    List<Future<Long>> futureList=exec.invokeAll(callList);  
    for(Future<Long> future:futureList){  
        sum+=future.get();  
    }  
    exec.shutdown();  
    System.out.println(sum);
  }
 }
	
 

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐