1. 程式人生 > >Java並發編程-Executor框架(轉)

Java並發編程-Executor框架(轉)

tco stat ive true 關閉 提交 strong dex runnable

本文轉自http://blog.csdn.net/chenchaofuck1/article/details/51606224 感謝作者

我們在傳統多線程編程創建線程時,常常是創建一些Runnable對象,然後創建對應的Thread對象執行它們,但是如果程序需要並發執行大量的任務時,需要為每個任務都創建一個Thread,進行管理,這將會影響程序的執行效率,並且創建線程過多將會使系統負載過重。

在JDK 1.5之後通過了一套Executor框架能夠解決這些問題,能夠分解任務的創建和執行過程。該框架包括Executor,ExecutorService,Callable等基礎接口和Executors,ThreadPoolExecutor

等實現類。

創建線程池:

Executor框架的最核心的類是ThreadPoolExecutor,它是線程池的實現類,創建ThreadPoolExecutor一般使用Executors工廠模式創建,Executors類提供了一系列工廠方法用於創先線程池:

  • public static ExecutorService newFixedThreadPool(int nThreads)創建固定數目線程的線程池,表示最多創建nThreads個線程,如果傳入的任務數大於nThreads時不會創建新的線程,而是阻塞等待有空閑線程執行。

  • public static ExecutorService newCachedThreadPool()創建一個可緩存的線程池,調用execute將重用以前構造的線程(如果線程可用)。

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

  • public static ExecutorService newSingleThreadExecutor()創建一個單線程的Executor。

  • public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) 創建一個支持定時及周期性的任務執行的線程池,多數情況下可用來替代Timer類。

常用方法:

  • shutDown():關閉執行器,在關閉前允許執行以前提交的任務執行器執行完。調用shutDown()後,再發送任務給Executor將會被拒絕,拋出RejectExecutionException異常。

  • shutdownNow() :立即關閉執行器,阻止等待任務啟動,並試圖停止當前正在執行的任務。返回等待執行的任務列表。

  • isShutdown():調用shutDown()後,返回true。

  • isTerminated():調用shutDown()後,並且執行器完成了關閉過程,返回true。

  • getPoolSize():獲取當前線程池的線程數量

  • getActiveCount():獲取線程池中活動線程的數量

  • getCompleteCount():獲取線程池中完成的任務數。

import java.util.concurrent.Executors; import java.util.concurrent.ThreadPoolExecutor; public class ExecutorTest { public static void main(String[] args){ ThreadPoolExecutor executor = (ThreadPoolExecutor)Executors.newCachedThreadPool(); for (int i = 0; i < 5; i++){ executor.execute(new task()); } executor.shutdown(); while(!executor.isTerminated()){ System.out.printf("Pool size:%d,Active count:%d,Completed Task:%d\n",executor.getPoolSize(),executor.getActiveCount(),executor.getCompletedTaskCount()); } } } class task implements Runnable{ public void run() { System.out.println(Thread.currentThread().getName() + " is called"); try { Thread.sleep(100); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }

結果:

pool-1-thread-2 is called
pool-1-thread-4 is called
pool-1-thread-5 is called
pool-1-thread-3 is called
pool-1-thread-1 is called
Pool size:5,Active count:5,Completed Task:0
Pool size:5,Active count:5,Completed Task:0
Pool size:5,Active count:5,Completed Task:0
Pool size:5,Active count:5,Completed Task:0

Java並發編程-Executor框架(轉)