java併發編程-Executor框架

Executor框架是指java 5中引入的一系列併發庫中與executor相關的一些功能類,其中包括線程池,Executor,Executors,ExecutorService,CompletionService,Future,Callable等。他們的關係爲:


 

併發編程的一種編程方式是把任務拆分爲一些列的小任務,即Runnable,然後在提交給一個Executor執行,Executor.execute(Runnalbe)。Executor在執行時使用內部的線程池完成操作。

一、創建線程池

Executors類,提供了一系列工廠方法用於創先線程池,返回的線程池都實現了ExecutorService接口。

public static ExecutorService newFixedThreadPool(int nThreads)

創建固定數目線程的線程池。

public static ExecutorService newCachedThreadPool()

創建一個可緩存的線程池,調用execute 將重用以前構造的線程(如果線程可用)。如果現有線程沒有可用的,則創建一個新線程並添加到池中。終止並從緩存中移除那些已有 60 秒鐘未被使用的線程。

public static ExecutorService newSingleThreadExecutor()

創建一個單線程化的Executor。

public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize)

創建一個支持定時及週期性的任務執行的線程池,多數情況下可用來替代Timer類。

Java代碼  收藏代碼
  1. Executor executor = Executors.newFixedThreadPool(10);  
  2. Runnable task = new Runnable() {  
  3.     @Override  
  4.     public void run() {  
  5.         System.out.println("task over");  
  6.     }  
  7. };  
  8. executor.execute(task);  
  9.   
  10. executor = Executors.newScheduledThreadPool(10);  
  11. ScheduledExecutorService scheduler = (ScheduledExecutorService) executor;  
  12. scheduler.scheduleAtFixedRate(task, 1010, TimeUnit.SECONDS);  

 二、ExecutorService與生命週期

ExecutorService擴展了Executor並添加了一些生命週期管理的方法。一個Executor的生命週期有三種狀態,運行關閉終止。Executor創建時處於運行狀態。當調用ExecutorService.shutdown()後,處於關閉狀態,isShutdown()方法返回true。這時,不應該再想Executor中添加任務,所有已添加的任務執行完畢後,Executor處於終止狀態,isTerminated()返回true。

如果Executor處於關閉狀態,往Executor提交任務會拋出unchecked exception RejectedExecutionException。

Java代碼  收藏代碼
  1. ExecutorService executorService = (ExecutorService) executor;  
  2. while (!executorService.isShutdown()) {  
  3.     try {  
  4.         executorService.execute(task);  
  5.     } catch (RejectedExecutionException ignored) {  
  6.           
  7.     }  
  8. }  
  9. executorService.shutdown();  

 三、使用Callable,Future返回結果

Future<V>代表一個異步執行的操作,通過get()方法可以獲得操作的結果,如果異步操作還沒有完成,則,get()會使當前線程阻塞。FutureTask<V>實現了Future<V>和Runable<V>。Callable代表一個有返回值得操作。

Java代碼  收藏代碼
  1. Callable<Integer> func = new Callable<Integer>(){  
  2.     public Integer call() throws Exception {  
  3.         System.out.println("inside callable");  
  4.         Thread.sleep(1000);  
  5.         return new Integer(8);  
  6.     }         
  7. };        
  8. FutureTask<Integer> futureTask  = new FutureTask<Integer>(func);  
  9. Thread newThread = new Thread(futureTask);  
  10. newThread.start();  
  11.   
  12. try {  
  13.     System.out.println("blocking here");  
  14.     Integer result = futureTask.get();  
  15.     System.out.println(result);  
  16. catch (InterruptedException ignored) {  
  17. catch (ExecutionException ignored) {  
  18. }  

 ExecutoreService提供了submit()方法,傳遞一個Callable,或Runnable,返回Future。如果Executor後臺線程池還沒有完成Callable的計算,這調用返回Future對象的get()方法,會阻塞直到計算完成。

例子:並行計算數組的和。

Java代碼  收藏代碼
  1. package executorservice;  
  2.   
  3. import java.util.ArrayList;  
  4. import java.util.List;  
  5. import java.util.concurrent.Callable;  
  6. import java.util.concurrent.ExecutionException;  
  7. import java.util.concurrent.ExecutorService;  
  8. import java.util.concurrent.Executors;  
  9. import java.util.concurrent.Future;  
  10. import java.util.concurrent.FutureTask;  
  11.   
  12. public class ConcurrentCalculator {  
  13.   
  14.     private ExecutorService exec;  
  15.     private int cpuCoreNumber;  
  16.     private List<Future<Long>> tasks = new ArrayList<Future<Long>>();  
  17.   
  18.     // 內部類  
  19.     class SumCalculator implements Callable<Long> {  
  20.         private int[] numbers;  
  21.         private int start;  
  22.         private int end;  
  23.   
  24.         public SumCalculator(final int[] numbers, int start, int end) {  
  25.             this.numbers = numbers;  
  26.             this.start = start;  
  27.             this.end = end;  
  28.         }  
  29.   
  30.         public Long call() throws Exception {  
  31.             Long sum = 0l;  
  32.             for (int i = start; i < end; i++) {  
  33.                 sum += numbers[i];  
  34.             }  
  35.             return sum;  
  36.         }  
  37.     }  
  38.   
  39.     public ConcurrentCalculator() {  
  40.         cpuCoreNumber = Runtime.getRuntime().availableProcessors();  
  41.         exec = Executors.newFixedThreadPool(cpuCoreNumber);  
  42.     }  
  43.   
  44.     public Long sum(final int[] numbers) {  
  45.         // 根據CPU核心個數拆分任務,創建FutureTask並提交到Executor  
  46.         for (int i = 0; i < cpuCoreNumber; i++) {  
  47.             int increment = numbers.length / cpuCoreNumber + 1;  
  48.             int start = increment * i;  
  49.             int end = increment * i + increment;  
  50.             if (end > numbers.length)  
  51.                 end = numbers.length;  
  52.             SumCalculator subCalc = new SumCalculator(numbers, start, end);  
  53.             FutureTask<Long> task = new FutureTask<Long>(subCalc);  
  54.             tasks.add(task);  
  55.             if (!exec.isShutdown()) {  
  56.                 exec.submit(task);  
  57.             }  
  58.         }  
  59.         return getResult();  
  60.     }  
  61.   
  62.     /** 
  63.      * 迭代每個只任務,獲得部分和,相加返回 
  64.      *  
  65.      * @return 
  66.      */  
  67.     public Long getResult() {  
  68.         Long result = 0l;  
  69.         for (Future<Long> task : tasks) {  
  70.             try {  
  71.                 // 如果計算未完成則阻塞  
  72.                 Long subSum = task.get();  
  73.                 result += subSum;  
  74.             } catch (InterruptedException e) {  
  75.                 e.printStackTrace();  
  76.             } catch (ExecutionException e) {  
  77.                 e.printStackTrace();  
  78.             }  
  79.         }  
  80.         return result;  
  81.     }  
  82.   
  83.     public void close() {  
  84.         exec.shutdown();  
  85.     }  
  86. }  

 Main

Java代碼  收藏代碼
  1. int[] numbers = new int[] { 123456781011 };  
  2. ConcurrentCalculator calc = new ConcurrentCalculator();  
  3. Long sum = calc.sum(numbers);  
  4. System.out.println(sum);  
  5. calc.close();  

 四、CompletionService

在剛在的例子中,getResult()方法的實現過程中,迭代了FutureTask的數組,如果任務還沒有完成則當前線程會阻塞,如果我們希望任意字任務完成後就把其結果加到result中,而不用依次等待每個任務完成,可以使CompletionService。生產者submit()執行的任務。使用者take()已完成的任務,並按照完成這些任務的順序處理它們的結果。也就是調用CompletionService的take方法是,會返回按完成順序放回任務的結果,CompletionService內部維護了一個阻塞隊列BlockingQueue,如果沒有任務完成,take()方法也會阻塞。修改剛纔的例子使用CompletionService:

Java代碼  收藏代碼
  1. public class ConcurrentCalculator2 {  
  2.   
  3.     private ExecutorService exec;  
  4.     private CompletionService<Long> completionService;  
  5.   
  6.   
  7.     private int cpuCoreNumber;  
  8.   
  9.     // 內部類  
  10.     class SumCalculator implements Callable<Long> {  
  11.         ......  
  12.     }  
  13.   
  14.     public ConcurrentCalculator2() {  
  15.         cpuCoreNumber = Runtime.getRuntime().availableProcessors();  
  16.         exec = Executors.newFixedThreadPool(cpuCoreNumber);  
  17.         completionService = new ExecutorCompletionService<Long>(exec);  
  18.   
  19.   
  20.     }  
  21.   
  22.     public Long sum(final int[] numbers) {  
  23.         // 根據CPU核心個數拆分任務,創建FutureTask並提交到Executor  
  24.         for (int i = 0; i < cpuCoreNumber; i++) {  
  25.             int increment = numbers.length / cpuCoreNumber + 1;  
  26.             int start = increment * i;  
  27.             int end = increment * i + increment;  
  28.             if (end > numbers.length)  
  29.                 end = numbers.length;  
  30.             SumCalculator subCalc = new SumCalculator(numbers, start, end);   
  31.             if (!exec.isShutdown()) {  
  32.                 completionService.submit(subCalc);  
  33.   
  34.   
  35.             }  
  36.               
  37.         }  
  38.         return getResult();  
  39.     }  
  40.   
  41.     /** 
  42.      * 迭代每個只任務,獲得部分和,相加返回 
  43.      *  
  44.      * @return 
  45.      */  
  46.     public Long getResult() {  
  47.         Long result = 0l;  
  48.         for (int i = 0; i < cpuCoreNumber; i++) {              
  49.             try {  
  50.                 Long subSum = completionService.take().get();  
  51.                 result += subSum;             
  52.             } catch (InterruptedException e) {  
  53.                 e.printStackTrace();  
  54.             } catch (ExecutionException e) {  
  55.                 e.printStackTrace();  
  56.             }  
  57.         }  
  58.         return result;  
  59.     }  
  60.   
  61.     public void close() {  
  62.         exec.shutdown();  
  63.     }  
  64. }  

 五、例子HtmlRender

該例子模擬瀏覽器的Html呈現過程,先呈現文本,再異步下載圖片,下載完畢每個圖片即顯示,見附件eclipse項目htmlreander包。

 

所有代碼見附件,Eclipse項目。本文參考《Java併發編程實踐》。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章