ThreadPoolExecutor线程大于corePoolsize的多出线程是咋产生的( 二 )

private boolean addIfUnderCorePoolSize(Runnable firstTask) { Thread t = null; final ReentrantLock mainLock = this.mainLock; mainLock.lock(); try { if (poolSize \u0026lt; corePoolSize \u0026amp;\u0026amp; runState == RUNNING) t = addThread(firstTask); } finally { mainLock.unlock(); } return t != null; } !addIfUnderCorePoolSize(command) 在什么情况下会返回true从而进入if方法内呢?if方法内将runnable任务添加到queue中或者执行max的方法在多线程并发情况下:并发执行execute方法,由于execute方法中没有加锁(锁加在了addIfUnderCorePoolSize方法中,因为这个方法中加锁逻辑少于外面加锁,用于提高效率)于是就会出现锁外 poolSize \u0026lt; corePoolSize 但是 锁内部poolSize \u0026gt;= corePoolSize 的情况,这样执行流程也会进入if方法内。private Thread addThread(Runnable firstTask) { Worker w = new Worker(firstTask); Thread t = threadFactory.newThread(w); boolean workerStarted = false; if (t != null) { if (t.isAlive()) // precheck that t is startable throw new IllegalThreadStateException(); w.thread = t; workers.add(w); int nt = ++poolSize; if (nt \u0026gt; largestPoolSize) largestPoolSize = nt; try { t.start(); workerStarted = true; } finally { if (!workerStarted) workers.remove(w); } } return t; }(4)注意:private boolean addIfUnderMaximumPoolSize(Runnable firstTask) { Thread t = null; final ReentrantLock mainLock = this.mainLock; mainLock.lock(); try { if (poolSize \u0026lt; maximumPoolSize \u0026amp;\u0026amp; runState == RUNNING) t = addThread(firstTask); } finally { mainLock.unlock(); } return t != null; }------------------------------------------------------------------------------更详细的介绍请参看Java的ThreadPoolExecutor类是如何让线程进入timed_waiting状态的? - 郭无心的回答这里介绍下ThreadPoolExecutor当中锁的应用上文也提到了:(1)private final ReentrantLock mainLock = new ReentrantLock(); 互斥锁 也称为独占锁:同一时间只有一个线程获取锁,再有线程尝试加锁,将失败。(2)支持 awaitTermination的条件变量 private final Condition termination = mainLock.newCondition();维护的并发操作:1:存放执行线程的HashSet(因为HashSet是线程不安全的) /** * Set containing all worker threads in pool. Accessed only when * holding mainLock. */ private final HashSet\u0026lt;Worker\u0026gt; workers = new HashSet\u0026lt;Worker\u0026gt;();2. 记录该线程池当中曾经出现过的最大的线程数量(每次增加线程时都会拿workers的size与记录量进行比较,如果大于,则更新该值) /** * Tracks largest attained pool size. Accessed only under * mainLock. */ private int largestPoolSize;


推荐阅读