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

比如ThreadPoolExecutor当中的一些方法:获取曾经在线程池当中出现过的最大线程数,需要mainLock锁加锁/** * Returns the largest number of threads that have ever * simultaneously been in the pool. * * @return the number of threads */public int getLargestPoolSize() { final ReentrantLock mainLock = this.mainLock; mainLock.lock(); try { return largestPoolSize; } finally { mainLock.unlock(); }}//增加线程private boolean addWorker(Runnable firstTask, boolean core) { retry: for (;;) { int c = ctl.get(); int rs = runStateOf(c); // Check if queue empty only if necessary. if (rs \u0026gt;= SHUTDOWN \u0026amp;\u0026amp; ! (rs == SHUTDOWN \u0026amp;\u0026amp; firstTask == null \u0026amp;\u0026amp; ! workQueue.isEmpty())) return false; for (;;) { int wc = workerCountOf(c); if (wc \u0026gt;= CAPACITY || wc \u0026gt;= (core ? corePoolSize : maximumPoolSize)) return false; if (compareAndIncrementWorkerCount(c)) break retry; c = ctl.get(); // Re-read ctl if (runStateOf(c) != rs) continue retry; // else CAS failed due to workerCount change; retry inner loop } } Worker w = new Worker(firstTask); Thread t = w.thread; final ReentrantLock mainLock = this.mainLock; mainLock.lock(); try { // Recheck while holding lock. // Back out on ThreadFactory failure or if // shut down before lock acquired. int c = ctl.get(); int rs = runStateOf(c); if (t == null || (rs \u0026gt;= SHUTDOWN \u0026amp;\u0026amp; ! (rs == SHUTDOWN \u0026amp;\u0026amp; firstTask == null))) { decrementWorkerCount(); tryTerminate(); return false; } workers.add(w); int s = workers.size(); if (s \u0026gt; largestPoolSize) largestPoolSize = s; } finally { mainLock.unlock(); } t.start(); // It is possible (but unlikely) for a thread to have been // added to workers, but not yet started, during transition to // STOP, which could result in a rare missed interrupt, // because Thread.interrupt is not guaranteed to have any effect // on a non-yet-started Thread (see Thread#interrupt). if (runStateOf(ctl.get()) == STOP \u0026amp;\u0026amp; ! t.isInterrupted()) t.interrupt(); return true; }
■网友
首先,我这里贴张图,帮助你理解下线程池的工作任务的处理流程。
ThreadPoolExecutor线程大于corePoolsize的多出线程是咋产生的


推荐阅读