1. private Runnable getTask() {
  2. boolean timedOut = false; // Did the last poll() time out?
  3. for (;;) {
  4. int c = ctl.get();
  5. int rs = runStateOf(c);
  6. // Check if queue empty only if necessary.
  7. if (rs >= SHUTDOWN && (rs >= STOP || workQueue.isEmpty())) {
  8. decrementWorkerCount();
  9. return null;
  10. }
  11. int wc = workerCountOf(c);
  12. // 削减条件
  13. boolean timed = allowCoreThreadTimeOut || wc > corePoolSize;
  14. // 这里是线程个数是否删除的关键
  15. if ((wc > maximumPoolSize || (timed && timedOut))
  16. && (wc > 1 || workQueue.isEmpty())) {
  17. if (compareAndDecrementWorkerCount(c))
  18. return null;
  19. continue;
  20. }
  21. try {
  22. // 这里才是最核心的所在
  23. Runnable r = timed ?
  24. workQueue.poll(keepAliveTime, TimeUnit.NANOSECONDS) :
  25. workQueue.take();
  26. if (r != null)
  27. return r;
  28. timedOut = true;
  29. } catch (InterruptedException retry) {
  30. timedOut = false;
  31. }
  32. }
  33. }

结论:

1.workerCount不可能一直maxSize
2.线程池中的可用线程大于1时候,只有满足削减条件(削减条件:workerCount > coreSize或者允许核心线程超时),并且超时了,才会削减线程个数
3.线程池中的可用线程为1,只有满足削减条件(削减条件:workerCount > coreSize或者允许核心线程超时),而且队列为空,才会减少线程个数为0