創(chuàng)建線程池的構(gòu)造函數(shù)如下:
public ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory, RejectedExecutionHandler handler) { if (corePoolSize < 0 || maximumPoolSize <= 0 || maximumPoolSize < corePoolSize || keepAliveTime < 0) throw new IllegalArgumentException(); if (workQueue == null || threadFactory == null || handler == null) throw new NullPointerException(); this.acc = System.getSecurityManager() == null ? null : AccessController.getContext(); this.corePoolSize = corePoolSize; this.maximumPoolSize = maximumPoolSize; this.workQueue = workQueue; this.keepAliveTime = unit.toNanos(keepAliveTime); this.threadFactory = threadFactory; this.handler = handler; }
?
corePoolSize? ? ? ? | 核心線程數(shù),線程池中最小線程數(shù),即使線程空閑,也不會(huì)被銷(xiāo)毀;任務(wù)首先提交到核心線程中執(zhí)行。(初始化時(shí)不創(chuàng)建線程,提交任務(wù)時(shí)創(chuàng)建線程)(如果設(shè)置allowCoreThreadTimeOut為true,核心線程也會(huì)被銷(xiāo)毀,使用較少) |
maximumPoolSize | 線程池中允許創(chuàng)建的最大線程數(shù)。 |
keepAliveTime | 當(dāng)線程數(shù)大于corePoolSize時(shí),線程最多等待keepAliveTime時(shí)間后,將被銷(xiāo)毀。 |
unit | keepAliveTime參數(shù)的時(shí)間單位,一般為毫秒。 |
workQueue | 提交任務(wù)的緩存隊(duì)列。 |
threadFactory | 創(chuàng)建線程的工廠。 |
handler | 當(dāng)corePoolSize已滿,緩存隊(duì)列已滿,maximumPoolSize已滿時(shí),又發(fā)生任務(wù)提交時(shí)的處理器。 |
?
提交任務(wù)時(shí):
如果線程數(shù)小于核心線程數(shù)(corePoolSize)(或者核心線程有空閑),則新創(chuàng)建線程(或者使用空閑線程)執(zhí)行任務(wù);
如果線程數(shù)等于核心線程數(shù),則將任務(wù)緩存到隊(duì)列(workQueue);
如果緩存隊(duì)列已滿,則繼續(xù)創(chuàng)建線程執(zhí)行任務(wù),直到達(dá)到最大線程數(shù);
如果線程數(shù)達(dá)到最大線程數(shù)(maximumPoolSize),再提交任務(wù),將使用handler來(lái)處理無(wú)法處理的任務(wù)。
本文摘自 :https://www.cnblogs.com/