核心線程會一直存活,即使它們處于閑置狀態。非核心線程閑置超過超時時長會被回收。
一、線程池優點
1.重用線程,避免線程創建和銷毀帶來的開銷。
2.有效控制線程池最大并發數,避免大量線程因互相搶占系統資源導致阻塞。
3.方便管理,提供定時執行和間隔循環執行。
二、ThreadPoolExecutor
android線程池概念來源于java的Executor接口,真正的實現是ThreadPoolExecutor。android四種線程池就是通過配置ThreadPoolExecutor來實現的。常見構造方法如下:
public ThreadPoolExecutor(int corePoolSize,int maximumPoolSize,long keepAliveTime,
TimeUnit unit,BlockingQueue<Runnable> workQueue,ThreadFactory threadFactory)
- corePoolSize
線程池的核心線程數。默認情況下,核心線程會一直存活,即使它們處于閑置狀態。 - maximumPoolSize
線程池中可容納的最大線程數。當活動線程達到這個數目后,后續新任務被阻塞。 - keepAliveTime
非核心線程閑置時的超時時長,超過此時長,會被回收。當ThreadPoolExecutor的allowCoreThreadTimeout設置為true時,keepAliveTime同樣會作用于核心線程。 - unit
指定keepAliveTime的時間位。常見枚舉常量有TimeUnit.MILLISECONDS、TimeUnit.SECONDS、TimeUnit.MINUTES - BlockingQueue<Runnable> workQueue
線程池中的任務隊列 - ThreadFactory threadFactory
線程工廠,為線程池創建新線程。
三、分析各種線程池
AsyncTask 源代碼略
核心線程數等于CPU核心數+1
最大線程數等于CPU核心數*2+1
默認情況下核心線程會在線程池中一直存活,即使它們處于閑置狀態
非核心線程通過keepAliveTime設置閑置時長,超時會被回收。
任務隊列容量128:new LinkedBlockingQueue<Runnable>(128);
FixedThreadPool
只有核心線程,并且沒有超時機制,任務隊列沒有大小限制。
它能快速地響應外界的請求。
public static ExecutorService newFixedThreadPool(int nThreads){
return new ThreadPoolExecutor(nThreads,nThreads,0L,
TimeUnit.MILLISECONDS,new LinkedBlockingQueue<Runnable>());
}
- CachedThreadPool
public static ExecutorService newCachedThreadPool(){
return new ThreadPoolExecutor(0,Integer.MAX_VALUE,60L,
TimeUnit.SECONDS,new SynchronousQueue<Runnable>());
}
只有非核心線程,并且數量不限??臻e線程超時時長60秒。
比較適合執行大量耗時較少的任務。當整個線程池處于閑置狀態時,都會超時被停止,幾乎不會占用任何系統資源。
- ScheduledThreadPool
public static ExecutorService newScheduledThreadPool(int corePoolSize){
return new ThreadPoolExecutor(corePoolSize,Integer.MAX_VALUE,0L,
TimeUnit.SECONDS,new DelayedWorkQueue<Runnable>());
}
核心線程數量固定的,非核心線程數沒有限制。主要用于執行定時任務和具有固定周期的重復任務。
- SingleThreadExecutor
public static ExecutorService newSingleThreadExecutor(){
return new ThreadPoolExecutor(1,1,0L,
TimeUnit.SECONDS,new LinkedBlockingQueue<Runnable>());
}
只有一個核心線程,統一所有外界任務到一個線程中,使得這些任務間不需要處理線程同步的問題。