ThreadPoolExecutor
線程池的真正實現,它的構造方法提供了一系列參數來配置線程池。
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue,
ThreadFactory threadFactory,
RejectedExecutionHandler handler)
corePoolSize:線程池的核心線程數
maximumPoolSize:線程池所能容納的最大線程數
keepAliveTime:非核心線程閑置時的超時時長,超過這個時長,非核心線程就會被回收
unit:指定keepAliveTime參數的時間單位
workQueue:線程池的任務隊列,通過線程池的execute方法提交的Runnable對象會存儲在這個參數中
threadFactory:線程工廠,為線程池提供創建新線程的功能
handler:任務隊列已滿或無法成功執行任務時的處理方式
Android中常用的線程池
FixedThreadPool,CachedThreadPool,ScheduledThreadPool,SingleThreadExecutor
1.FixedThreadPool:線程數量固定的線程池(只有核心線程且核心線程不會被回收)
public static ExecutorService newFixedThreadPool(int nThreads) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
}
2.CachedThreadPool:線程數量不定的線程池,只有非核心線程,且最大線程數為
Integer.MAX_VALUE(主要用于執行大量的耗時較少的任務)。
public static ExecutorService newCachedThreadPool() {
return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>());
}
3.ScheduledThreadPool:核心線程數固定,非核心線程無限制,且非核心線程閑置時會被立即回收(主要用于執行定時任務和具有固定周期的重復任務)。
public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) {
return new ScheduledThreadPoolExecutor(corePoolSize);
}
public ScheduledThreadPoolExecutor(int corePoolSize) {
super(corePoolSize, Integer.MAX_VALUE,
DEFAULT_KEEPALIVE_MILLIS, MILLISECONDS,
new DelayedWorkQueue());
}
4.SingleThreadExecutor:只有一個核心線程,確保所有的任務都在同一個線程中按順序執行
public static ExecutorService newSingleThreadExecutor() {
return new FinalizableDelegatedExecutorService
(new ThreadPoolExecutor(1, 1,0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>()));
}