創(chuàng)建線(xiàn)程池的構(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? ? ? ? | 核心線(xiàn)程數(shù),線(xiàn)程池中最小線(xiàn)程數(shù),即使線(xiàn)程空閑,也不會(huì)被銷(xiāo)毀;任務(wù)首先提交到核心線(xiàn)程中執(zhí)行。(初始化時(shí)不創(chuàng)建線(xiàn)程,提交任務(wù)時(shí)創(chuàng)建線(xiàn)程)(如果設(shè)置allowCoreThreadTimeOut為true,核心線(xiàn)程也會(huì)被銷(xiāo)毀,使用較少) |
maximumPoolSize | 線(xiàn)程池中允許創(chuàng)建的最大線(xiàn)程數(shù)。 |
keepAliveTime | 當(dāng)線(xiàn)程數(shù)大于corePoolSize時(shí),線(xiàn)程最多等待keepAliveTime時(shí)間后,將被銷(xiāo)毀。 |
unit | keepAliveTime參數(shù)的時(shí)間單位,一般為毫秒。 |
workQueue | 提交任務(wù)的緩存隊(duì)列。 |
threadFactory | 創(chuàng)建線(xiàn)程的工廠。 |
handler | 當(dāng)corePoolSize已滿(mǎn),緩存隊(duì)列已滿(mǎn),maximumPoolSize已滿(mǎn)時(shí),又發(fā)生任務(wù)提交時(shí)的處理器。 |
?
提交任務(wù)時(shí):
如果線(xiàn)程數(shù)小于核心線(xiàn)程數(shù)(corePoolSize)(或者核心線(xiàn)程有空閑),則新創(chuàng)建線(xiàn)程(或者使用空閑線(xiàn)程)執(zhí)行任務(wù);
如果線(xiàn)程數(shù)等于核心線(xiàn)程數(shù),則將任務(wù)緩存到隊(duì)列(workQueue);
如果緩存隊(duì)列已滿(mǎn),則繼續(xù)創(chuàng)建線(xiàn)程執(zhí)行任務(wù),直到達(dá)到最大線(xiàn)程數(shù);
如果線(xiàn)程數(shù)達(dá)到最大線(xiàn)程數(shù)(maximumPoolSize),再提交任務(wù),將使用handler來(lái)處理無(wú)法處理的任務(wù)。
本文摘自 :https://www.cnblogs.com/