java線(xiàn)程池種我常用的創(chuàng)建方法
ExecutorService executor = Executors.newFixedThreadPool(20);
ExecutorService executor = Executors.newCachedThreadPool();
ExecutorService executor = Executors.newSingleThreadExecutor();
newFixedThreadPool
Executors是一個(gè)類(lèi),里面提供多種比較方便快捷的靜態(tài)方法操作創(chuàng)建線(xiàn)程池
Executors.newFixedThreadPool(20)方法里面返回的是一個(gè)ThreadPoolExecutor對(duì)象,ThreadPoolExecutor類(lèi)繼承了AbstractExecutorService類(lèi),而AbstractExecutorService類(lèi)又實(shí)現(xiàn)了ExecutorService接口。ThreadPoolExecutor里面提供了多種構(gòu)造函數(shù)。
public static ExecutorService newFixedThreadPool(int nThreads) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
}
newFixedThreadPool方法的corePoolSize,maximumPoolSize參數(shù)值是一樣的,keepAliveTime(線(xiàn)程空閑時(shí)的存活時(shí)間,即當(dāng)線(xiàn)程沒(méi)有任務(wù)執(zhí)行時(shí),繼續(xù)存活的時(shí)間;默認(rèn)情況下,該參數(shù)只在線(xiàn)程數(shù)大于corePoolSize時(shí)才有用)傳入的是0,阻塞隊(duì)列使用的是LinkedBlockingQueue
在線(xiàn)程池中總共設(shè)置了有4種阻塞隊(duì)列
1、ArrayBlockingQueue:基于數(shù)組結(jié)構(gòu)的有界阻塞隊(duì)列,按FIFO排序任務(wù);
2、LinkedBlockingQuene:基于鏈表結(jié)構(gòu)的阻塞隊(duì)列,按FIFO排序任務(wù),吞吐量通常要高于ArrayBlockingQuene;
3、SynchronousQuene:一個(gè)不存儲(chǔ)元素的阻塞隊(duì)列,每個(gè)插入操作必須等到另一個(gè)線(xiàn)程調(diào)用移除操作,否則插入操作一直處于阻塞狀態(tài),吞吐量通常要高于LinkedBlockingQuene;
4、priorityBlockingQuene:具有優(yōu)先級(jí)的無(wú)界阻塞隊(duì)列;
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue) {
this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
Executors.defaultThreadFactory(), defaultHandler);
}
進(jìn)入到ThreadPoolExecutor類(lèi)中后,在其構(gòu)造方法中還會(huì)有兩個(gè)默認(rèn)的參數(shù)創(chuàng)建線(xiàn)程的工廠(chǎng)ThreadFactory和線(xiàn)程池的飽和策略RejectedExecutionHandler。
線(xiàn)程的飽和策略也默認(rèn)有4中
1、AbortPolicy直接拋出異常,默認(rèn)策略
2、CallerRunsPolicy使用調(diào)用者所在的線(xiàn)程來(lái)處理任務(wù)
3、DiscardOldestPolicy拋棄隊(duì)列中最靠前的任務(wù),并執(zhí)行當(dāng)前的任務(wù)
4、DiscardPolicy直接丟棄任務(wù)
注:也可以根據(jù)應(yīng)用場(chǎng)景實(shí)現(xiàn)RejectedExecutionHandler接口,自定義飽和策略,如記錄日志或持久化存儲(chǔ)不能處理的任務(wù)。
newCachedThreadPool
Executors.newCachedThreadPool()里面給ThreadPoolExecutor類(lèi)傳入的參數(shù)是核心線(xiàn)程corePoolSize為0,maximumPoolSize為整型的最大值,超時(shí)時(shí)間設(shè)置成60s,阻塞隊(duì)列選用SynchronousQuene
public static ExecutorService newCachedThreadPool() {
return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>());
}
newSingleThreadExecutor
newSingleThreadExecutor初始化的線(xiàn)程池中只有一個(gè)線(xiàn)程,如果該線(xiàn)程異常結(jié)束,會(huì)重新創(chuàng)建一個(gè)新的線(xiàn)程繼續(xù)執(zhí)行任務(wù),唯一的線(xiàn)程可以保證所提交任務(wù)的順序執(zhí)行,內(nèi)部使用LinkedBlockingQueue作為阻塞隊(duì)列。
public static ExecutorService newSingleThreadExecutor() {
return new FinalizableDelegatedExecutorService
(new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>()));
}