核心線程會(huì)一直存活,即使它們處于閑置狀態(tài)饵骨。非核心線程閑置超過超時(shí)時(shí)長會(huì)被回收。
一茫打、線程池優(yōu)點(diǎn)
1.重用線程居触,避免線程創(chuàng)建和銷毀帶來的開銷。
2.有效控制線程池最大并發(fā)數(shù)老赤,避免大量線程因互相搶占系統(tǒng)資源導(dǎo)致阻塞轮洋。
3.方便管理,提供定時(shí)執(zhí)行和間隔循環(huán)執(zhí)行抬旺。
二弊予、ThreadPoolExecutor
android線程池概念來源于java的Executor接口,真正的實(shí)現(xiàn)是ThreadPoolExecutor开财。android四種線程池就是通過配置ThreadPoolExecutor來實(shí)現(xiàn)的汉柒。常見構(gòu)造方法如下:
public ThreadPoolExecutor(int corePoolSize,int maximumPoolSize,long keepAliveTime,
TimeUnit unit,BlockingQueue<Runnable> workQueue,ThreadFactory threadFactory)
- corePoolSize
線程池的核心線程數(shù)误褪。默認(rèn)情況下,核心線程會(huì)一直存活碾褂,即使它們處于閑置狀態(tài)兽间。 - maximumPoolSize
線程池中可容納的最大線程數(shù)。當(dāng)活動(dòng)線程達(dá)到這個(gè)數(shù)目后正塌,后續(xù)新任務(wù)被阻塞嘀略。 - keepAliveTime
非核心線程閑置時(shí)的超時(shí)時(shí)長,超過此時(shí)長乓诽,會(huì)被回收屎鳍。當(dāng)ThreadPoolExecutor的allowCoreThreadTimeout設(shè)置為true時(shí),keepAliveTime同樣會(huì)作用于核心線程问裕。 - unit
指定keepAliveTime的時(shí)間位逮壁。常見枚舉常量有TimeUnit.MILLISECONDS、TimeUnit.SECONDS粮宛、TimeUnit.MINUTES - BlockingQueue<Runnable> workQueue
線程池中的任務(wù)隊(duì)列 - ThreadFactory threadFactory
線程工廠窥淆,為線程池創(chuàng)建新線程。
三巍杈、分析各種線程池
AsyncTask 源代碼略
核心線程數(shù)等于CPU核心數(shù)+1
最大線程數(shù)等于CPU核心數(shù)*2+1
默認(rèn)情況下核心線程會(huì)在線程池中一直存活忧饭,即使它們處于閑置狀態(tài)
非核心線程通過keepAliveTime設(shè)置閑置時(shí)長,超時(shí)會(huì)被回收筷畦。
任務(wù)隊(duì)列容量128:new LinkedBlockingQueue<Runnable>(128);
FixedThreadPool
只有核心線程词裤,并且沒有超時(shí)機(jī)制,任務(wù)隊(duì)列沒有大小限制鳖宾。
它能快速地響應(yīng)外界的請求吼砂。
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>());
}
只有非核心線程,并且數(shù)量不限鼎文∮婕纾空閑線程超時(shí)時(shí)長60秒。
比較適合執(zhí)行大量耗時(shí)較少的任務(wù)拇惋。當(dāng)整個(gè)線程池處于閑置狀態(tài)時(shí)周偎,都會(huì)超時(shí)被停止,幾乎不會(huì)占用任何系統(tǒng)資源撑帖。
- ScheduledThreadPool
public static ExecutorService newScheduledThreadPool(int corePoolSize){
return new ThreadPoolExecutor(corePoolSize,Integer.MAX_VALUE,0L,
TimeUnit.SECONDS,new DelayedWorkQueue<Runnable>());
}
核心線程數(shù)量固定的蓉坎,非核心線程數(shù)沒有限制。主要用于執(zhí)行定時(shí)任務(wù)和具有固定周期的重復(fù)任務(wù)胡嘿。
- SingleThreadExecutor
public static ExecutorService newSingleThreadExecutor(){
return new ThreadPoolExecutor(1,1,0L,
TimeUnit.SECONDS,new LinkedBlockingQueue<Runnable>());
}
只有一個(gè)核心線程蛉艾,統(tǒng)一所有外界任務(wù)到一個(gè)線程中,使得這些任務(wù)間不需要處理線程同步的問題。