ThreadPoolExecutor线程池学习

线程池的五种状态

以下状态描述取自jdk1.8 ThreadPoolExecutor源码中的注释描述,源文档如下:

    /** The runState provides the main lifecycle control, taking on values:
     *
     *   RUNNING:  Accept new tasks and process queued tasks
     *   SHUTDOWN: Don't accept new tasks, but process queued tasks
     *   STOP:     Don't accept new tasks, don't process queued tasks,
     *             and interrupt in-progress tasks
     *   TIDYING:  All tasks have terminated, workerCount is zero,
     *             the thread transitioning to state TIDYING
     *             will run the terminated() hook method
     *   TERMINATED: terminated() has completed
     */    

线程池使用32位的前三位作为线程池的状态位,如下标红的即为状态位

RUNNING

接受新任务,并处理队列中的任务

源码中的定义如下:

//COUNT_BITS = Integer.SIZE - 3 = 32 - 3 = 29
//Integer 占四个字节 1byte = 8bit, 4byte = 32bit
private static final int RUNNING    = -1 << COUNT_BITS;

对应二进制格式如下(32bit):

11100000000000000000
SHUTDOWN

不接受新任务,但处理队列中的任务

源码中的定义如下:

//COUNT_BITS = Integer.SIZE - 3 = 32 - 3 = 29
//Integer 占四个字节 1byte = 8bit, 4byte = 32bit
private static final int SHUTDOWN   =  0 << COUNT_BITS;

对应二进制格式如下(32bit):

00000000000000000000
STOP

不接受新任务,不处理排队的任务,中断正在进行的任务

源码中的定义如下:

//COUNT_BITS = Integer.SIZE - 3 = 32 - 3 = 29
//Integer 占四个字节 1byte = 8bit, 4byte = 32bit
private static final int STOP       =  1 << COUNT_BITS;

对应二进制格式如下(32bit):

00100000000000000000
TIDYING

所有任务都已终止,workerCount 为零,转换到状态 TIDYING 的线程将运行 terminated() 钩子方法(terminated()方法的默认是空实现)

源码中的定义如下:

//COUNT_BITS = Integer.SIZE - 3 = 32 - 3 = 29
//Integer 占四个字节 1byte = 8bit, 4byte = 32bit
private static final int TIDYING    =  2 << COUNT_BITS;

对应二进制格式如下(32bit):

01000000000000000000
TERMINATED

terminated() 已完成

源码中的定义如下:

//COUNT_BITS = Integer.SIZE - 3 = 32 - 3 = 29
//Integer 占四个字节 1byte = 8bit, 4byte = 32bit
private static final int TERMINATED =  3 << COUNT_BITS;

对应二进制格式如下(32bit):

01100000000000000000

线程池的状态转换

状态转换如下图所示,根据源码注释描述画出

   /** The numerical order among these values matters, to allow
     * ordered comparisons. The runState monotonically increases over
     * time, but need not hit each state. The transitions are:
     *
     * RUNNING -> SHUTDOWN
     *    On invocation of shutdown(), perhaps implicitly in finalize()
     * (RUNNING or SHUTDOWN) -> STOP
     *    On invocation of shutdownNow()
     * SHUTDOWN -> TIDYING
     *    When both queue and pool are empty
     * STOP -> TIDYING
     *    When pool is empty
     * TIDYING -> TERMINATED
     *    When the terminated() hook method has completed
     */
在调用shutdown时
在调用shutdownNow时
在调用shutdownNow时
当队列和池都为空时
当池为空时
当terminated钩子方法完成时
RUNNING
SHUTDOWN
STOP
TIDYING
TERMINATED
ThreadPoolExecutor状态转换

简略图

在这里插入图片描述

源码

除了状态常量以外的常量

// 主池控制状态ctl是一个原子整数,封装了两个概念字段: 
// runState: 前3位,表示是否正在运行、正在关闭等
// workerCount: 后29位,表示有效线程数,
// 111 00000000000000000000000000000
private final AtomicInteger ctl = new AtomicInteger(ctlOf(RUNNING, 0));
// 总位数: 32 -3 
private static final int COUNT_BITS = Integer.SIZE - 3;
// 线程池容量,前3位是runState,后29位是workerCount: 000 11111111111111111111111111111 = (2 ^ 29) - 1
private static final int CAPACITY   = (1 << COUNT_BITS) - 1;
execute(Runnable command)
public void execute(Runnable command) {
        if (command == null)
            throw new NullPointerException();
        /*
         * Proceed in 3 steps:
         *
         * 1. If fewer than corePoolSize threads are running, try to
         * start a new thread with the given command as its first
         * task.  The call to addWorker atomically checks runState and
         * workerCount, and so prevents false alarms that would add
         * threads when it shouldn't, by returning false.
         *
         * 2. If a task can be successfully queued, then we still need
         * to double-check whether we should have added a thread
         * (because existing ones died since last checking) or that
         * the pool shut down since entry into this method. So we
         * recheck state and if necessary roll back the enqueuing if
         * stopped, or start a new thread if there are none.
         *
         * 3. If we cannot queue task, then we try to add a new
         * thread.  If it fails, we know we are shut down or saturated
         * and so reject the task.
         */
        int c = ctl.get();
    	// 当前工作线程数是否小于核心线程,表示可以新增核心工作线程
        if (workerCountOf(c) < corePoolSize) {
            // 新增工作线程,成功后则return
            if (addWorker(command, true))
                return;
            // 执行到这里说明新增核心线程失败了,重新获取状态
            c = ctl.get();
        }
    	// isRunning(c) : 判断线程池是否运行状态(其他调用方可能调用了shutdown等方法改变了线程池状态)
    	// workQueue.offer(command) : 向阻塞队列中添加任务,添加成功则返回true,失败则返回false
        if (isRunning(c) && workQueue.offer(command)) {
            // 拿到状态再次检查
            int recheck = ctl.get();
            // 线程池状态未运行 && 移除任务成功,若线程池状态不是运行中,则尝试移除这个任务
            if (! isRunning(recheck) && remove(command))
                // 任务从队列中移除成功,执行拒绝策略
                reject(command);
            else if (workerCountOf(recheck) == 0) 
                // 如果当前没有存活的工作线程,则创建一个
                addWorker(null, false);
        }
    	// 添加非核心线程
        else if (!addWorker(command, false))
            // 添加失败了,执行拒绝策略
            reject(command);
    }
addWorker(Runnable firstTask, boolean core)
private boolean addWorker(Runnable firstTask, boolean core) {
  		// 标记
        retry:
        for (;;) {
            int c = ctl.get();
            int rs = runStateOf(c);

            // 仅在必要时检查队列是否为空
            // 线程池不再接收新任务,且  !(线程池状态为 shutdown && 任务为空 && 工作队列不为空)
            // 这里有疑问!!!
            if (rs >= SHUTDOWN &&
                ! (rs == SHUTDOWN &&
                   firstTask == null &&
                   ! workQueue.isEmpty()))
                return false;

            for (;;) {
                // 拿到当前工作线程数
                int wc = workerCountOf(c);
                if (wc >= CAPACITY ||
                    wc >= (core ? corePoolSize : maximumPoolSize))
                    // 工作线程数达到容量限制,或达到了核心线程数/最大核心线程数限制,则返回失败
                    return false;
                // CAS将工作线程数 数量+1
                if (compareAndIncrementWorkerCount(c))
                    // 数量递增成功,跳到标记处,不再进入循环,执行后续逻辑
                    break retry;
                // 到这里说明cas失败了,重新读取状态
                c = ctl.get();  // Re-read ctl
                if (runStateOf(c) != rs)
                    // 线程池状态发生了改变,跳到外循环,重新执行
                    continue retry;
                // 否则 CAS 由于 workerCount 变化而失败;重试内循环
                // else CAS failed due to workerCount change; retry inner loop
            }
        }
		// 工作线程是否启动成功
        boolean workerStarted = false;
    	// 工作线程是否添加成功
        boolean workerAdded = false;
        Worker w = null;
        try {
            // 封装为Worker对象
            w = new Worker(firstTask);
            // 这里的thread是由线程工厂生成的
            final Thread t = w.thread;
            if (t != null) {
                final ReentrantLock mainLock = this.mainLock;
                mainLock.lock();
                try {
                    // 在拿到锁后再次获取状态并检查,防止在拿锁前,线程池被停止
                    int rs = runStateOf(ctl.get());
			
                    // 线程池是运行中 或 线程池状态为不接受新任务(可执行队列中任务)且新任务为空时
                    if (rs < SHUTDOWN ||
                        (rs == SHUTDOWN && firstTask == null)) {
                        // 重新检测线程t是可启动的
                        if (t.isAlive()) // precheck that t is startable
                            throw new IllegalThreadStateException();
                        // 将工作线程添加到工作线程集合中
                        workers.add(w);
                        int s = workers.size();
                        // 设置最大线程池数量,记录峰值用
                        if (s > largestPoolSize)
                            largestPoolSize = s;
                        // 工作线程已添加成功
                        workerAdded = true;
                    }
                } finally {
                    // 释放主锁
                    mainLock.unlock();
                }
                if (workerAdded) {
                    // 若工作线程添加成功,则启动工作线程
                    t.start();
                    workerStarted = true;
                }
            }
        } finally {
            if (! workerStarted)
                // 若启动失败,则执行添加工作线程失败方法
                addWorkerFailed(w);
        }
        return workerStarted;
    }

还有几个核心方法没写,待补充…

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值