多线程并发计算数据

来源:互联网 发布:战地4 mac版下载地址 编辑:程序博客网 时间:2024/05/29 18:26
  1. import java.util.ArrayList;  
  2. import java.util.List;  
  3. import java.util.concurrent.Callable;  
  4. import java.util.concurrent.ExecutionException;  
  5. import java.util.concurrent.ExecutorService;  
  6. import java.util.concurrent.Executors;  
  7. import java.util.concurrent.Future;  
  8.   
  9.   
  10. public class LargSumWithCallable {  
  11.       
  12.     static int threadCounts =10;//使用的线程数    
  13.     static long sum=0;   
  14.       
  15.   public static void main(String []args) throws InterruptedException, ExecutionException{  
  16.       
  17.            
  18.        
  19.     ExecutorService exec=Executors.newFixedThreadPool(threadCounts);    
  20.     List<Callable<Long>> callList=new ArrayList<Callable<Long>>();    
  21.    
  22.     List<Integer> list = new ArrayList<Integer>();  
  23.       
  24.     for (int j = 0; j <= 1000000;j++)  {    
  25.         list.add(j);    
  26.     }  
  27.        
  28.     int len=list.size()/threadCounts;//平均分割List    
  29.     //List中的数量没有线程数多(很少存在)    
  30.     if(len==0){    
  31.         threadCounts=list.size();//采用一个线程处理List中的一个元素    
  32.         len=list.size()/threadCounts;//重新平均分割List    
  33.     }    
  34.     for(int i=0;i<threadCounts;i++){    
  35.         final List<Integer> subList;    
  36.         if(i==threadCounts-1){    
  37.             subList=list.subList(i*len,list.size());    
  38.         }else{    
  39.             subList=list.subList(i*len, len*(i+1)>list.size()?list.size():len*(i+1));    
  40.         }    
  41.         //采用匿名内部类实现    
  42.         callList.add(new Callable<Long>(){    
  43.             public Long call() throws Exception {    
  44.                 long subSum=0L;    
  45.                 for(Integer i:subList){    
  46.                     subSum+=i;    
  47.                 }    
  48.                 System.out.println("分配给线程:"+Thread.currentThread().getName()+"那一部分List的整数和为:\tSubSum:"+subSum);    
  49.                 return subSum;    
  50.             }    
  51.         });    
  52.     }    
  53.     List<Future<Long>> futureList=exec.invokeAll(callList);    
  54.     for(Future<Long> future:futureList){    
  55.         sum+=future.get();    
  56.     }    
  57.     exec.shutdown();    
  58.     System.out.println(sum);  
  59.   }  
  60.  }  
  61.      方案2
    1. import java.util.ArrayList;  
    2. import java.util.List;  
    3. import java.util.concurrent.BrokenBarrierException;  
    4. import java.util.concurrent.CyclicBarrier;  
    5. import java.util.concurrent.ExecutorService;  
    6. import java.util.concurrent.Executors;  
    7.   
    8.   
    9. public class LargeListIntegerSum {  
    10.    
    11.         private long sum;//存放整数的和    
    12.         private CyclicBarrier barrier;//障栅集合点(同步器)    
    13.         private List<Integer> list;//整数集合List    
    14.         private int threadCounts;//使用的线程数    
    15.         public LargeListIntegerSum(List<Integer> list,int threadCounts) {    
    16.             this.list=list;    
    17.             this.threadCounts=threadCounts;    
    18.         }    
    19.         /**  
    20.          * 获取List中所有整数的和  
    21.          * @return  
    22.          */    
    23.         public long getIntegerSum(){    
    24.             ExecutorService exec=Executors.newFixedThreadPool(threadCounts);    
    25.             int len=list.size()/threadCounts;//平均分割List    
    26.             //List中的数量没有线程数多(很少存在)    
    27.             if(len==0){    
    28.                 threadCounts=list.size();//采用一个线程处理List中的一个元素    
    29.                 len=list.size()/threadCounts;//重新平均分割List    
    30.             }    
    31.             barrier=new CyclicBarrier(threadCounts+1);    
    32.             for(int i=0;i<threadCounts;i++){    
    33.                 //创建线程任务    
    34.                 if(i==threadCounts-1){//最后一个线程承担剩下的所有元素的计算    
    35.                     exec.execute(new SubIntegerSumTask(list.subList(i*len,list.size())));    
    36.                 }else{    
    37.                     exec.execute(new SubIntegerSumTask(list.subList(i*len, len*(i+1)>list.size()?list.size():len*(i+1))));    
    38.                 }    
    39.             }    
    40.             try {    
    41.                 barrier.await();//关键,使该线程在障栅处等待,直到所有的线程都到达障栅处    
    42.             } catch (InterruptedException e) {    
    43.                 System.out.println(Thread.currentThread().getName()+":Interrupted");    
    44.             } catch (BrokenBarrierException e) {    
    45.                 System.out.println(Thread.currentThread().getName()+":BrokenBarrier");    
    46.             }    
    47.             exec.shutdown();    
    48.             return sum;    
    49.         }    
    50.         /**  
    51.          * 分割计算List整数和的线程任务  
    52.           
    53.          *  
    54.          */    
    55.         public class SubIntegerSumTask implements Runnable{    
    56.             private List<Integer> subList;    
    57.             public SubIntegerSumTask(List<Integer> subList) {    
    58.                 this.subList=subList;    
    59.             }    
    60.             public void run() {    
    61.                 long subSum=0L;    
    62.                 for (Integer i : subList) {    
    63.                     subSum += i;    
    64.                 }      
    65.                 synchronized(LargeListIntegerSum.this){//在LargeListIntegerSum对象上同步    
    66.                     sum+=subSum;    
    67.                 }    
    68.                 try {    
    69.                     barrier.await();//关键,使该线程在障栅处等待,直到所有的线程都到达障栅处    
    70.                 } catch (InterruptedException e) {    
    71.                     System.out.println(Thread.currentThread().getName()+":Interrupted");    
    72.                 } catch (BrokenBarrierException e) {    
    73.                     System.out.println(Thread.currentThread().getName()+":BrokenBarrier");    
    74.                 }    
    75.                 System.out.println("分配给线程:"+Thread.currentThread().getName()+"那一部分List的整数和为:\tSubSum:"+subSum);    
    76.             }    
    77.                 
    78.         }    
    79.       
    80.           
    81.         public static void main(String[] args) {    
    82.             List<Integer> list = new ArrayList<Integer>();    
    83.             int threadCounts = 10;//采用的线程数    
    84.              
    85.             for (int i = 1; i <= 1000000; i++) {    
    86.                 list.add(i);    
    87.             }    
    88.               
    89.             long start=  System.currentTimeMillis();  
    90.             LargeListIntegerSum countListIntegerSum=new LargeListIntegerSum(list,threadCounts);   
    91.             
    92.             long sum=countListIntegerSum.getIntegerSum();         
    93.             System.out.println("List中所有整数的和为:"+sum);   
    94.             long end=  System.currentTimeMillis();       
    95.             System.out.println(end-start);    
    96.         }    
    97.       
    98. }  

  62.    
原创粉丝点击