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