多線程並發快速處理數據


方法1

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);
  }
 }
   

 

方法2

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;


public class LargeListIntegerSum {
 
        private long sum;//存放整數的和  
        private CyclicBarrier barrier;//障柵集合點(同步器)  
        private List<Integer> list;//整數集合List  
        private int threadCounts;//使用的線程數  
        public LargeListIntegerSum(List<Integer> list,int threadCounts) {  
            this.list=list;  
            this.threadCounts=threadCounts;  
        }  
        /**
         * 獲取List中所有整數的和
         * @return
         */  
        public long getIntegerSum(){  
            ExecutorService exec=Executors.newFixedThreadPool(threadCounts);  
            int len=list.size()/threadCounts;//平均分割List  
            //List中的數量沒有線程數多(很少存在)  
            if(len==0){  
                threadCounts=list.size();//采用一個線程處理List中的一個元素  
                len=list.size()/threadCounts;//重新平均分割List  
            }  
            barrier=new CyclicBarrier(threadCounts+1);  
            for(int i=0;i<threadCounts;i++){  
                //創建線程任務  
                if(i==threadCounts-1){//最后一個線程承擔剩下的所有元素的計算  
                    exec.execute(new SubIntegerSumTask(list.subList(i*len,list.size())));  
                }else{  
                    exec.execute(new SubIntegerSumTask(list.subList(i*len, len*(i+1)>list.size()?list.size():len*(i+1))));  
                }  
            }  
            try {  
                barrier.await();//關鍵,使該線程在障柵處等待,直到所有的線程都到達障柵處  
            } catch (InterruptedException e) {  
                System.out.println(Thread.currentThread().getName()+":Interrupted");  
            } catch (BrokenBarrierException e) {  
                System.out.println(Thread.currentThread().getName()+":BrokenBarrier");  
            }  
            exec.shutdown();  
            return sum;  
        }  
        /**
         * 分割計算List整數和的線程任務
         
         *
         */  
        public class SubIntegerSumTask implements Runnable{  
            private List<Integer> subList;  
            public SubIntegerSumTask(List<Integer> subList) {  
                this.subList=subList;  
            }  
            public void run() {  
                long subSum=0L;  
                for (Integer i : subList) {  
                    subSum += i;  
                }    
                synchronized(LargeListIntegerSum.this){//在LargeListIntegerSum對象上同步  
                    sum+=subSum;  
                }  
                try {  
                    barrier.await();//關鍵,使該線程在障柵處等待,直到所有的線程都到達障柵處  
                } catch (InterruptedException e) {  
                    System.out.println(Thread.currentThread().getName()+":Interrupted");  
                } catch (BrokenBarrierException e) {  
                    System.out.println(Thread.currentThread().getName()+":BrokenBarrier");  
                }  
                System.out.println("分配給線程:"+Thread.currentThread().getName()+"那一部分List的整數和為:\tSubSum:"+subSum);  
            }  
              
        }  
    
        
        public static void main(String[] args) {  
            List<Integer> list = new ArrayList<Integer>();  
            int threadCounts = 10;//采用的線程數  
           
            for (int i = 1; i <= 1000000; i++) {  
                list.add(i);  
            }  
            
            long start=  System.currentTimeMillis();
            LargeListIntegerSum countListIntegerSum=new LargeListIntegerSum(list,threadCounts);
          
            long sum=countListIntegerSum.getIntegerSum();          
            System.out.println("List中所有整數的和為:"+sum);
            long end=  System.currentTimeMillis();     
            System.out.println(end-start);  
        }  
    
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM