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; }
■网友
首先,我这里贴张图,帮助你理解下线程池的工作任务的处理流程。
推荐阅读
- 豪车|玛莎拉蒂推出限量版新车,噱头大于实际意义
- 将ipad应用于课堂是利大于弊还是弊大于利
- 汽车知识|形式大于内容,长安CS75百万版上市,中期改款主要是换壳
- 现在很多都是无限流量了iPhone大于150MB的app不能下载,有没有大佬有啥好的办法解决
- 这些体检项目 套路大于实效,慎做!
- 多线程编程中join这个单词为啥有等待结束的意思
- 钟南山|钟南山:人的寿命应该大于100岁!他的5句话,每个人都该听听
- 车之养护|都知道7座车噱头大于实际,那为什么不考虑买6座呢?
- 怎样理解servlet单例引起的线程安全问题
- 使用无锁队列还是线程同步锁?
