使用線程池的好處
可以歸納為3點(diǎn):
- 重用線程池中的線程, 避免因?yàn)榫€程的創(chuàng)建和銷毀所帶來的性能開銷.
- 有效控制線程池中的最大并發(fā)數(shù)震叮,避免大量線程之間因?yàn)橄嗷屨枷到y(tǒng)資源而導(dǎo)致的阻塞現(xiàn)象.
- 能夠?qū)€程進(jìn)行簡(jiǎn)單的管理蠢古,可提供定時(shí)執(zhí)行和按照指定時(shí)間間隔循環(huán)執(zhí)行等功能.
線程池真正的實(shí)現(xiàn)類是ThreadPoolExecutor帮坚,它間接實(shí)現(xiàn)了Executor接口。
ThreadPoolExecutor提供了一系列參數(shù)來配置線程池珍坊,通過不同的參數(shù)配置實(shí)現(xiàn)不同功能特性的線程池.
Android為了方便開發(fā)者創(chuàng)建4種不同特性的ThreadPoolExecutor侵状, 提供了一個(gè)Executors類李破,提供了4個(gè)靜態(tài)工廠方法.
eg. newFixedThreadPool().
public class Executors {
public static ExecutorService newFixedThreadPool(int nThreads) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
}
}
ThreadPoolExecutor 構(gòu)造方法的配置參數(shù)
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue,
ThreadFactory threadFactory,
RejectedExecutionHandler handler) {
}
corePoolSize: 線程池的核心線程數(shù),默認(rèn)情況下壹将, 核心線程會(huì)在線程池中一直存活, 即使處于閑置狀態(tài).
但如果將allowCoreThreadTimeOut設(shè)置為true的話, 那么核心線程也會(huì)有超時(shí)機(jī)制毛嫉, 在keepAliveTime設(shè)置的時(shí)間過后诽俯, 核心線程也會(huì)被終止.
maximumPoolSize: 最大的線程數(shù), 包括核心線程承粤, 也包括非核心線程暴区, 在線程數(shù)達(dá)到這個(gè)值后,新來的任務(wù)將會(huì)被阻塞.
keepAliveTime: 超時(shí)的時(shí)間辛臊, 閑置的非核心線程超過這個(gè)時(shí)長(zhǎng)仙粱,將會(huì)被銷毀回收, 當(dāng)allowCoreThreadTimeOut為true時(shí)彻舰,這個(gè)值也作用于核心線程.
unit:超時(shí)時(shí)間的時(shí)間單位.
workQueue:線程池的任務(wù)隊(duì)列伐割, 通過execute方法提交的runnable對(duì)象會(huì)存儲(chǔ)在這個(gè)隊(duì)列中.
threadFactory: 線程工廠, 為線程池提供創(chuàng)建新線程的功能.
handler: 任務(wù)無法執(zhí)行時(shí),回調(diào)handler的rejectedExecution方法來通知調(diào)用者.
線程池的分類, 4個(gè)
FixedThreadPool 固定大小線程池
用法
ExecutorService fixedThreadPool = Executors.newFixedThreadPool(num);
fixedThreadPool.execute(runnable對(duì)象);
public static ExecutorService newFixedThreadPool(int nThreads) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
}
特點(diǎn):只有核心線程數(shù)刃唤,并且沒有超時(shí)機(jī)制隔心,因此核心線程即使閑置時(shí),也不會(huì)被回收尚胞,因此能更快的響應(yīng)外界的請(qǐng)求.
使用場(chǎng)景: 需要快速響應(yīng)外界請(qǐng)求.
CachedThreadPool 只有非核心線程并且無限量的線程池
用法:
ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
cachedThreadPool.execute(runnable對(duì)象);
public static ExecutorService newCachedThreadPool() {
return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>());
}
特點(diǎn):沒有核心線程硬霍,非核心線程數(shù)量沒有限制, 超時(shí)為60秒.
使用場(chǎng)景: 適用于執(zhí)行大量耗時(shí)較少的任務(wù)笼裳,當(dāng)線程閑置超過60秒時(shí)就會(huì)被系統(tǒng)回收掉唯卖,當(dāng)所有線程都被系統(tǒng)回收后粱玲,它幾乎不占用任何系統(tǒng)資源.
ScheduledThreadPool 執(zhí)行定時(shí)任務(wù)的線程池
ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(int corePoolSize);
scheduledThreadPool.schedule(runnable對(duì)象, 2000, TimeUnit.MILLISECONDS);
public ScheduledThreadPoolExecutor(int corePoolSize) {
super(corePoolSize, Integer.MAX_VALUE, 0, NANOSECONDS,
new DelayedWorkQueue());
}
特點(diǎn):核心線程數(shù)是固定的,非核心線程數(shù)量沒有限制拜轨, 沒有超時(shí)機(jī)制.
使用場(chǎng)景: 主要用于執(zhí)行定時(shí)任務(wù)和具有固定周期的重復(fù)任務(wù).
SingleThreadExecutor 只有一個(gè)核心線程的線程池
用法:
ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor();
singleThreadExecutor.execute(runnable對(duì)象);
public static ExecutorService newSingleThreadExecutor() {
return new FinalizableDelegatedExecutorService
(new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>()));
}
特點(diǎn):只有一個(gè)核心線程抽减,并沒有超時(shí)機(jī)制.
使用場(chǎng)景: 意義在于統(tǒng)一所有的外界任務(wù)到一個(gè)線程中, 這使得在這些任務(wù)之間不需要處理線程同步的問題.
AsyncTask的底層實(shí)現(xiàn)使用的就是ThreadPoolExecutor
核心線程數(shù)為: 手機(jī)CPU數(shù)+1
最大線程數(shù)為: 手機(jī)CPU數(shù)*2 +1
任務(wù)隊(duì)列BlockingQueue的容量為: 128
public abstract class AsyncTask<Params, Progress, Result> {
private static final int CPU_COUNT = Runtime.getRuntime().availableProcessors();//CPU數(shù)
private static final int CORE_POOL_SIZE = CPU_COUNT + 1;
private static final int MAXIMUM_POOL_SIZE = CPU_COUNT * 2 + 1;
private static final int KEEP_ALIVE = 1;
private static final ThreadFactory sThreadFactory = new ThreadFactory() {
private final AtomicInteger mCount = new AtomicInteger(1);
public Thread newThread(Runnable r) {
return new Thread(r, "AsyncTask #" + mCount.getAndIncrement());
}
};
private static final BlockingQueue<Runnable> sPoolWorkQueue =
new LinkedBlockingQueue<Runnable>(128);
//static的撩轰, 因此所有整個(gè)進(jìn)程中胯甩, AsyncTask只有一個(gè)線程池.
public static final Executor THREAD_POOL_EXECUTOR
= new ThreadPoolExecutor(CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE,
TimeUnit.SECONDS, sPoolWorkQueue, sThreadFactory);
}
-----DONE.----------