ThreadPoolExecutor源码分析

114 阅读3分钟

概述

本文通过分析ThreadPoolExecutor源码,能够学习到如何维护线程池状态,execute方法执行顺序,维护核心线程、非核心线程,何时销毁非核心线程等知识。

内部状态

private static final int COUNT_BITS = Integer.SIZE - 3;
// Integer.SIZE = 32
// 29
// 0001 1101
private static final int COUNT_MASK = (1 << COUNT_BITS) - 1;
// 536870911
// 0001 1111 1111 1111 1111 1111 1111 1111

/**
 * 使用高三位标识线程池状态
 * 111-RUNNING-可以接受新任务
 * 000-SHUTDOWN-不接受新任务但是可以处理已添加的任务
 * 001-STOP-不接受新任务,不处理已有任务,中断正在处理的任务
 * 010-TIDYING-所有任务已终止
 * 011-TERMINATED-线程池彻底终止
 */
private static final int RUNNING    = -1 << COUNT_BITS;
// -536,870,912
// 1110 0000 0000 0000 0000 0000 0000 0000
private static final int SHUTDOWN   =  0 << COUNT_BITS;
// 0
// 0000 0000 0000 0000 0000 0000 0000 0000
private static final int STOP       =  1 << COUNT_BITS; 
// 536,870,912
// 0010 0000 0000 0000 0000 0000 0000 0000
private static final int TIDYING    =  2 << COUNT_BITS;
// 1,073,741,824
// 0100 0000 0000 0000 0000 0000 0000 0000
private static final int TERMINATED =  3 << COUNT_BITS;
// 1,610,612,736
// 0110 0000 0000 0000 0000 0000 0000 0000

// 取高三位,判断线程池状态
private static int runStateOf(int c)     { return c & ~COUNT_MASK; }
// 取后29位,取出工作的线程数
private static int workerCountOf(int c)  { return c & COUNT_MASK; }
// 取出所有的1,线程池状态以及工作线程数
private static int ctlOf(int rs, int wc) { return rs | wc; }
// 保存线程池状态以及运行的线程数,高三位线程池状态,余下位数保存线程数
private final AtomicInteger ctl = new AtomicInteger(ctlOf(RUNNING, 0));

构造方法

// 内部有多个构造方法,最终都会执行此构造方法
public ThreadPoolExecutor(int corePoolSize,// 核心线程数
                          int maximumPoolSize,// 最大线程数
                          long keepAliveTime,// 线程存活时间
                          TimeUnit unit,// 上面一个参数的单位
                          BlockingQueue<Runnable> workQueue,// 阻塞队列
                          ThreadFactory threadFactory,// 线程工厂
                          RejectedExecutionHandler handler //拒绝策略) {
    if (corePoolSize < 0 ||
        maximumPoolSize <= 0 ||
        maximumPoolSize < corePoolSize ||
        keepAliveTime < 0)
        throw new IllegalArgumentException();
    if (workQueue == null || threadFactory == null || handler == null)
        throw new NullPointerException();
    this.corePoolSize = corePoolSize;
    this.maximumPoolSize = maximumPoolSize;
    this.workQueue = workQueue;
    this.keepAliveTime = unit.toNanos(keepAliveTime);
    this.threadFactory = threadFactory;
    this.handler = handler;
}

execute方法

1.接收任务后先增加核心线程数,超过核心线程数量后将任务加入队列

2.队列满了之后,增加非核心线程数量

3.非核心线程数量达到maximumPoolSize后,则执行拒绝策略

4.拒绝策略有四种,默认是抛出异常策略

public void execute(Runnable command) {
    if (command == null)
        throw new NullPointerException();
    
    int c = ctl.get();
    // 如果现有线程数小于核心线程数,则新建线程
    // 第一次进入,参考上面的位运算的分析,workerCountOf(c) = 0
    // 也就是说线程池创建后,内部并没有线程,随着任务加入执行而新建线程,直到大于核心线程不再新建
    if (workerCountOf(c) < corePoolSize) {
        // 新建线程
        if (addWorker(command, true))
            return;
        c = ctl.get();
    }
    // 加入队列
    if (isRunning(c) && workQueue.offer(command)) {
        int recheck = ctl.get();
        // 重新检查,是否查过限值
        if (! isRunning(recheck) && remove(command))
            reject(command);
        // 等于0的情况只有recheck=0或者recheck=STOP
        else if (workerCountOf(recheck) == 0)
            addWorker(null, false);
    }
    // 没能加入队列,则新建线程,新建线程失败则执行拒绝策略
    else if (!addWorker(command, false))
        reject(command);
}

addWorker

此方法比较长,核心就是增加线程数量,如果达到限值则返回false。增加线程数量后,调用线程的start方法

private boolean addWorker(Runnable firstTask, boolean core) {
        retry:
        for (int c = ctl.get();;) {
            // Check if queue empty only if necessary.
            // 线程池状态>=SHUTDOWN并且满足以下三个条件之一
            // 1.线程数量达到STOP 2.仍然传入任务,此时已不能再增加线程数量 3.阻塞队列为空时
            // 满足以上条件,则返回false,不能增加线程
            // 解释:1.已经达到最大数量,不能增加线程
            // 		 2.传入任务,此时应该加入阻塞队列,或者执行拒绝策略
            //		 3.线程已达到最大数量,已经把队列中的任务处理完毕,此时返回false
            if (runStateAtLeast(c, SHUTDOWN)
                && (runStateAtLeast(c, STOP)
                    || firstTask != null
                    || workQueue.isEmpty()))
                return false;

            for (;;) {
                // 如果大于corePoolSize或者maximumPoolSize,返回false,执行加入队列或者拒绝策略
                if (workerCountOf(c)
                    >= ((core ? corePoolSize : maximumPoolSize) & COUNT_MASK))
                    return false;
                // 线程数+1
                if (compareAndIncrementWorkerCount(c))
                    break retry;
                // 线程数自增失败,没有设置成功并且大于SHUTDOWN,此处进行循环
                c = ctl.get();  // Re-read ctl
                if (runStateAtLeast(c, SHUTDOWN))
                    continue retry;
                // else CAS failed due to workerCount change; retry inner loop
            }
        }

        boolean workerStarted = false;
        boolean workerAdded = false;
        Worker w = null;
        try {
            // 内部使用工厂新建一个线程
            w = new Worker(firstTask);
            final Thread t = w.thread;
            if (t != null) {
                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();
					// 判断c大于SHUTDOWN(0)时,则判断后面的
                    // c要小于STOP 并且firstTash == null
                    if (isRunning(c) ||
                        (runStateLessThan(c, STOP) && firstTask == null)) {
                        // 不是新建状态,则报错
                        if (t.getState() != Thread.State.NEW)
                            throw new IllegalThreadStateException();
                        // 线程加入HashSet
                        workers.add(w);
                        workerAdded = true;
                        int s = workers.size();
                        if (s > largestPoolSize)
                            largestPoolSize = s;
                    }
                } finally {
                    mainLock.unlock();
                }
                if (workerAdded) {
                    // 启动线程
                    t.start();
                    workerStarted = true;
                }
            }
        } finally {
            if (! workerStarted)
                addWorkerFailed(w);
        }
        return workerStarted;
    }

runWorker

线程启动后,不断的执行任务,直到队列中获取不到任务

// 调用start方法后,则会调用worker的run方法,
public void run() {
    runWorker(this);
}
// 调用ThreadPoolExecutor的runWorker
final void runWorker(Worker w) {
    Thread wt = Thread.currentThread();
    // 取出调用者的任务
    Runnable task = w.firstTask;
    w.firstTask = null;
    w.unlock(); // allow interrupts
    boolean completedAbruptly = true;
    try {
        // 不断循环,取出queue中的任务去执行
        while (task != null || (task = getTask()) != null) {
            w.lock();
            // ...
            try {
                // 省略若干代码
            } finally {
                task = null;
                w.completedTasks++;
                w.unlock();
            }
        }
        completedAbruptly = false;
    } finally {
        processWorkerExit(w, completedAbruptly);
    }
}

getTask

不断地从队列中返回任务,队列中任务执行完毕后,则去销毁非核心线程,核心线程默认不能超时销毁。

private Runnable getTask() {
    boolean timedOut = false; // Did the last poll() time out?

    for (;;) {
        int c = ctl.get();

        // Check if queue empty only if necessary.
        // 运行状态大于SHUTDOWN并且(1.运行状态大于等于STOP或者2.队列为空时)
        // 减少工作线程
        if (runStateAtLeast(c, SHUTDOWN)
            && (runStateAtLeast(c, STOP) || workQueue.isEmpty())) {
            decrementWorkerCount();
            return null;
        }
		// 计算现在的工作线程
        int wc = workerCountOf(c);

        // Are workers subject to culling?
        // allowCoreThreadTimeOut:核心线程默认不会超时销毁,默认值false
        // timed:超过corePoolSize的线程是否超时销毁标识
        boolean timed = allowCoreThreadTimeOut || wc > corePoolSize;

        // 1.如果超过了核心线程数(timed=true),并且timedOut=true(已经走过了一次循环,下文将timeOut改为true),
        // 意味着从队列中获取任务超时了
        // 2.工作线程数量大于1,或者队列为空时,cas减少工作线程数量
        // 前两者都满足则减少线程数量,否则,继续从队列中取出任务去执行
        if ((wc > maximumPoolSize || (timed && timedOut))
            && (wc > 1 || workQueue.isEmpty())) {
            if (compareAndDecrementWorkerCount(c))
                return null;
            continue;
        }

        try {
            // poll获取不到任务则会超时,超过核心线程数时,队列中获取不到任务就会超时,timedOut = true,下次循环减少工作线程
            // take获取不到任务则会阻塞,未超过核心线程数,阻塞等待
            Runnable r = timed ?
                workQueue.poll(keepAliveTime, TimeUnit.NANOSECONDS) :
            workQueue.take();
            if (r != null)
                return r;
            // 执行到这里说明已经超时,下次循环减少工作线程
            timedOut = true;
        } catch (InterruptedException retry) {
            timedOut = false;
        }
    }
}