一.线程池的创建

    1、如果线程池的当前大小还没有达到基本大小(poolSize < corePoolSize),那么就新增加一个线程处理新提交的任务;
    2、如果当前大小已经达到了基本大小,就将新提交的任务提交到阻塞队列排队,等候处理workQueue.offer(command);
    3、如果队列容量已达上限,并且当前大小poolSize没有达到maximumPoolSize,那么就新增线程来处理任务;
    4、如果队列已满,并且当前线程数目也已经达到上限,那么意味着线程池的处理能力已经达到了极限,此时需要拒绝新增加的任务。至于如何拒绝处理新增则需要看handle逻辑

    二.线程池的销毁
    线程获取task为null时自动销毁。
    1.当线程池中没有任务的时候.返回null

    1. // Check if queue empty only if necessary.
    2. if (rs >= SHUTDOWN && (rs >= STOP || workQueue.isEmpty())) {
    3. decrementWorkerCount();
    4. return null;
    5. }

    2.当线程池中当前线程大于最大线程数或者超时。返回null

    1. int wc = workerCountOf(c);
    2. // Are workers subject to culling?
    3. boolean timed = allowCoreThreadTimeOut || wc > corePoolSize;
    4. if ((wc > maximumPoolSize || (timed && timedOut))
    5. && (wc > 1 || workQueue.isEmpty())) {
    6. if (compareAndDecrementWorkerCount(c))
    7. return null;
    8. continue;
    9. }

    3.当线程池中当前线程超过核心线程同时设置了线程存活时间,使用BlockingQueue的阻塞poll。同时设置超时标识位为true;

    1. try {
    2. Runnable r = timed ?
    3. workQueue.poll(keepAliveTime, TimeUnit.NANOSECONDS) :
    4. workQueue.take();
    5. if (r != null)
    6. return r;
    7. timedOut = true;
    8. } catch (InterruptedException retry) {
    9. timedOut = false;
    10. }