Android中的線程池

?線程池的好處

1、重用線程池中的線程,避免線程的創(chuàng)建與銷毀帶來的性能開銷

2、能有效控制線程池的最大并發(fā)數(shù),避免大量線程因搶占資源而導(dǎo)致的阻塞

3、能對線程進行簡單的管理,提供定時或者指定間隔時間、循環(huán)執(zhí)行等操作

線程池的概率來自于java的Executor接口,實現(xiàn)類是ThreadPoolExecutor, 它提供一系列的參數(shù)來配置線程池,以此構(gòu)建不同的線程池。Android的線程池分4類,都是通過Executors所提供的工廠方法來得到。

ThreadPoolExecutor

ThreadPoolExecutor有四個構(gòu)造函數(shù),下面這個是最常用的

public?ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnnable> workQueue, ThreadFactory threadFactory)

corePoolSize

線程池中的核心線程數(shù),默認(rèn)情況下核心線程會在線程池中一直存活,即使他們處于閑置狀態(tài)。如果設(shè)置ThreadPoolExecutor 中的allowCoreThreadTimeOut = true, 核心線程在等待新任務(wù)到來時有超時機制,時間超過keepAliveTime所指定的時間后,核心線程會終止。

maximumPoolSize

最大線程數(shù)

keepAliveTime

非核心線程閑置的超時時間,超過這個時間,非核心線程會被回收。核心線程則要看allowCoreThreadTimeOut屬性的值。

unit

時間單位

workQueue

線程池中的工作隊列

threadFactory

線程工廠,為線程池提供創(chuàng)建新線程的功能。

舉個例子,我們常用的okhttp內(nèi)部也是使用了線程池,它的ThreadPoolExecutor主要是定義在Dispatcher類里面。 使用的是CachedThreadPool。

executorService = ThreadPoolExecutor(0, Int.MAX_VALUE, 60, TimeUnit.SECONDS, SynchronousQueue(), ThreadFactory("okhttp Dispatcher", false))

線程池的分類

1、FixedThreadPool

通過Executors的newFixedThreadPool()創(chuàng)建,這是一個線程數(shù)量固定的線程池,里面所有的線程都是核心線程。

public static ExecutorService newFixedThreadPool(int nThreads){

return new ThreadPoolExecutor(nThreads, nThreads, 0, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>())

}

2、CachedThreadPool

通過Executors的newCacheThreadPool()創(chuàng)建,這是一個線程數(shù)量不定的線程池,里面所有的線程都是非核心線程。最大線程數(shù)是無限大,當(dāng)線程池中的線程都處于活動狀態(tài)時,新的task會創(chuàng)建新的線程來處理,否則就使用空閑的線程處理,所有的線程都是60s的超時時間,超時后會自動回收。

public static ExecutorService?newFixedThreadPool(){

return new ThreadPoolExecutor(0,?Integer.MAX_VALUE, 60L, TimeUnit.SECONDS, new SynchronousQueue<Runnable>())

}

3、ScheduledThreadPool

通過Executors的newScheduledThreadPool()創(chuàng)建, 核心線程固定,非核心線程無限大,當(dāng)非核心線程空閑時,會立即被回收。適合做定時任務(wù)或者固定周期的重復(fù)任務(wù)。

public static ExecutorService?newScheduledThreadPool(int corePoolSize){

return new ThreadPoolExecutor(corePoolSize,?Integer.MAX_VALUE, 0, TimeUnit.SECONDS, new DelayedWorkQueue())

}

4、SingleThreadExcecutor

通過Executors的newSingleThreadPool()創(chuàng)建,內(nèi)部只有一個核心線程。

public static ExecutorService?newFixedThreadPool(){

return new ThreadPoolExecutor(1,?1, 0, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>())

}

課外知識:LinkedBlockingQueue

LinkedBlockingQueue是由鏈表組成的阻塞隊列,內(nèi)部head 指向隊列第一個元素,last指向最后一個元素。入隊和出隊都會加鎖阻塞,都是使用了不同的鎖。

DelayedWorkQueue

延時隊列,隊內(nèi)元素必須是Delayed的實現(xiàn)類。對內(nèi)元素會按照Delayed時間進行排序,對內(nèi)元素只有在delayed時間過期了才能出隊。

入隊的時候不阻塞隊列,出隊的時候,如果隊列為空或者隊列里所有元素都等待時間都沒有到期,則該線程進入阻塞狀態(tài)。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容