java 线程池的使用及原理(二):线程池的状态及证明

本文介绍Java线程池的五种状态:Running、ShutDown、Stop、Tidying、Terminated,包括各状态间的转换及如何通过ctl值获取线程池状态与线程个数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

线程的状态具有运行与关闭的状态,那么线程池也不例外。java线程池具有 5 种状态:Running、ShutDown、Stop、Tidying、Terminated。

在这里插入图片描述

线程池状态解析

1. Running

  • 线程池一旦被初始化,就是Running状态。也就是说,线程池被一旦被创建,就处于RUNNING状态,当然,此时线程池中的任务数为0。
    • private final AtomicInteger ctl = new AtomicInteger(ctlOf(RUNNING, 0));
    • 底层就是执行这句代码实现的 RUNNING 状态,有兴趣的可以深入了解一下
  • 在RUNNING状态下,可以接收新任务,也可以对原有任务进行处理。
  • 调用 shutdown() 方法,Running ==> ShutDown 状态
  • 调用 shutdownNow() 方法,Running状态 ==> Stop 状态

2. ShutDown

  • ShutDown 即关闭状态,不接收新任务,但能处理已添加的任务。
  • 当队列为空且任务全部执行完毕时,会 ShutDown 状态 ==> Tidying 状态

3. Stop

  • ShutDown 即停止状态,不接收新任务,不处理已添加的任务,并且会中断正在处理的任务。
  • 当执行任务为空时,会 Stop 状态 ==> Tidying 状态

4. Tidying

  • 当所有的任务已终止,ctl记录的”任务数量”为0,线程池会变为TIDYING状态。
  • 调用 terminated() 函数,TIDYING状态 ==> TERMINATED 状态。

5. Terminated

  • Terminated 即终止状态。线程池彻底终止,就变成TERMINATED状态。

6. 线程池状态代码查验

温馨提示,要彻底看懂接下来的代码,跳转 java 位运算的简单理解

  • 线程池使用原子类 AtomicInteger ctl 存储线程状态
    • 利用 COUNT_BITS = 3 分割线程池状态与线程个数
    • 高位前 3 为存储线程池状态
      • 111 ==> RUNNING 状态
      • 000 ==> SHUTDOWN状态
      • 001 ==> STOP状态
      • 010 ==> TIDYING状态
      • 011 ==> TERMINATED状态
    • 低位 29 位存储线程个数
public class ThreadPoolTest {
	// private final AtomicInteger ctl = new AtomicInteger(ctlOf(RUNNING, 0));
    private static final int COUNT_BITS = Integer.SIZE - 3;
    // 存储线程个数
    private static final int CAPACITY   = (1 << COUNT_BITS) - 1;
    private static final int RUNNING    = -1 << COUNT_BITS;
    private static final int SHUTDOWN   =  0 << COUNT_BITS;
    private static final int STOP       =  1 << COUNT_BITS;
    private static final int TIDYING    =  2 << COUNT_BITS;
    private static final int TERMINATED =  3 << COUNT_BITS;

    // 高位补 0
    private static String getFormatStr(int num, int len) {
        String integerMaxValueStr = Integer.toBinaryString(num);
        int a = len;
        StringBuilder sb = new StringBuilder();
        int l = integerMaxValueStr.length();
        int i = 0;
        for (; a > 0; --a) {
            if (--l >= 0) {
                sb.append(integerMaxValueStr.charAt(l));
            } else {
                sb.append("0");
            }
            if (++i % 4 == 0) {
                if (a > 1) {
                    sb.append("-");
                }
                i = 0;
            }
        }
        return sb.reverse().toString();
    }
    public static void main(String[] args) {
         System.out.println("Integer.SIZE =       " + Integer.SIZE);
        System.out.println("RUNNING 的十进制:    " + RUNNING);
        System.out.println("RUNNING 的二进制:    " + getFormatStr(RUNNING, 32));
        System.out.println("SHUTDOWN 的十进制:   " + SHUTDOWN);
        System.out.println("SHUTDOWN 的二进制:   " + getFormatStr(SHUTDOWN, 32));
        System.out.println("STOP 的十进制:       " + STOP);
        System.out.println("STOP 的二进制:       " + getFormatStr(STOP, 32));
        System.out.println("TIDYING 的十进制:    " + TIDYING);
        System.out.println("TIDYING 的二进制:    " + getFormatStr(TIDYING, 32));
        System.out.println("TERMINATED 的十进制: " + TERMINATED);
        System.out.println("TERMINATED 的二进制: " + getFormatStr(TERMINATED, 32));
        System.out.println("CAPACITY 的十进制:   " + CAPACITY);
        System.out.println("CAPACITY 的二进制:   " + getFormatStr(CAPACITY, 32));

    }
}

在这里插入图片描述

7. 各种状态的检验

  • ThreadPoolExecutor 没有提供对外的 ctl 状态,只有 private,所以采用 debug 方式查验

7.1 Running 状态

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class RunningTest {
    public static int state = 0;
    public static void main(String[] args) {
        ThreadPoolExecutor threadPool = new ThreadPoolExecutor(50, 100,
                0L, TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue<Runnable>(1000));
        // 这里打断点
        System.out.println("线程是否 shutdown 状态:" + threadPool.isShutdown());
        
    }
}
/*
* 根据各种状态校验值与源码,可以看到,isShutdown 为false 的情况只有Running状态
public boolean isShutdown() {
    return ! isRunning(ctl.get());
}
private static boolean isRunning(int c) {
    return c < SHUTDOWN;
}
*/

在这里插入图片描述

7.2 ShutDown ==> TIDYING ==> Terminated状态

  • 为了查看 TIDYING 状态,选择继承 ThreadPoolExecutor,重写 terminated() 方法
import java.util.concurrent.*;

public class ShutDownTest extends ThreadPoolExecutor{
    public static int state = 0;
	public ShutDownTest(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue) {
        super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue);
    }

    @Override
    protected void terminated() {
    	// 这里是第二个断点
        System.out.println("==================");
//        super.terminated();
    }
    static ThreadPoolExecutor threadPool = null;
    public static void main(String[] args) throws InterruptedException {
        ThreadPoolExecutor threadPool = new ShutDownTest(50, 100,
                0L, TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue<Runnable>(1000));
        System.out.println("线程是否 shutdown 状态:" + threadPool.isShutdown());
        state++;
        threadPool.execute(() -> {
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        System.out.println("=======任务未执行完的 shutdown()======");
        threadPool.shutdown();
        // 这里是第一个断点
        System.out.println("线程是否 shutdown 状态:" + threadPool.isShutdown());
        Thread.sleep(3000);
        state++;
        // 这里是第三个断点
        System.out.println("线程是否 shutdown 状态:" + threadPool.isShutdown());
    }
}

  • 断点1:任务未执行完: ctl = 1 ==> 0000 0000 0000 0000 0000 0000 0000 0001,高三位 000,此时是shutdown
    在这里插入图片描述

  • 断点2:TIDYING 状态调用 terminated(),此时还未到 Terminated 状态
    在这里插入图片描述

  • terminated() 方法执行完成,此时已达 Terminated 状态。
    在这里插入图片描述

7.3 Stop ==> TIDYING ==> Terminated状态

  • 与 shutdown 类似,只不过关闭线程池调用的是 shutdownNow();
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class StopTest extends ThreadPoolExecutor{
    public static int state = 0;

    public StopTest(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue) {
        super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue);
    }

    @Override
    protected void terminated() {
        System.out.println("==================");
    }
    static ThreadPoolExecutor threadPool = null;
    public static void main(String[] args) throws InterruptedException {
        ThreadPoolExecutor threadPool = new StopTest(50, 100,
                0L, TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue<Runnable>(1000));
        state++;
        threadPool.execute(() -> {
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        System.out.println("=======任务未执行完的 shutdownNow()======");
        threadPool.shutdownNow();
        System.out.println("线程是否 shutdown 状态:" + threadPool.isShutdown());
        state++;
        System.out.println("线程是否 shutdown 状态:" + threadPool.isShutdown());

    }
}

  • Stop 状态
    在这里插入图片描述

  • TIDYING 状态 调用 terminated(),此时还未到 Terminated 状态

在这里插入图片描述

  • terminated()方法已完成,Terminated 状态
    在这里插入图片描述

8. Shutdown 与 Stop 的区别

  • Shutdown 会执行已有的任务
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class ShutdownAndStop {
    public static void main(String[] args) throws InterruptedException {
        ThreadPoolExecutor threadPool = new ThreadPoolExecutor(2, 5,
                0L, TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue<Runnable>(1000));

        new Thread(() -> {
            System.out.println("========== 我执行了 shutdown() =========");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
           
            threadPool.shutdown();
            // threadPool.shutdownNow();
        }).start();

        for(int i = 0; i < 10; i++) {
            int finalI = i;
            Thread.sleep(300);
            threadPool.execute(() -> {
                try {
                    Thread.sleep(3000);
                    System.out.println("======= 我被shutdown() 但是会执行 ====== i = " + finalI);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });
        }
    }
}

  • 会执行已经添加进线程池的任务,后添加进来的任务报错
    在这里插入图片描述

  • Stop 不会执行已有的任务

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class ShutdownAndStop {
    public static void main(String[] args) throws InterruptedException {
        ThreadPoolExecutor threadPool = new ThreadPoolExecutor(2, 5,
                0L, TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue<Runnable>(1000));

        new Thread(() -> {
            System.out.println("========== 我执行了 shutdown() =========");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
           
            // threadPool.shutdown();
            threadPool.shutdownNow();
        }).start();

        for(int i = 0; i < 10; i++) {
            int finalI = i;
            Thread.sleep(300);
            threadPool.execute(() -> {
                try {
                    Thread.sleep(3000);
                    System.out.println("======= 我被shutdown() 但是会执行 ====== i = " + finalI);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });
        }
    }
}
  • 任务执行了中断,后添加进来的任务同样报错
    在这里插入图片描述

9. 怎么通过 ctl 值获取正在执行任务的线程个数?

  • 假定现在为 Running 状态
    • 先来看 CAPACITY 参数,其定义 int CAPACITY = (1 << COUNT_BITS) - 1 = 1 << 29 - 1,即为 0001-1111-1111-1111-1111-1111-1111-1111
    • ctl 值后 29 位存储线程个数,假定现在执行任务的线程为 2,即 ctl 为 1110-0000-0000-0000-0000-0000-0000-0010
  • 将 ctl & CAPACITY 即可得到对应的线程个数
    ctl值     :      1110-0000-0000-0000-0000-0000-0000-0010 
CAPACITY值    :      0001-1111-1111-1111-1111-1111-1111-1111
-----------------------------------------------------
ctl & CAPACITY:      0000-0000-0000-0000-0000-0000-0000-0010  ==> 2

10. 怎么通过 ctl 值获取线程池状态?

  • 将 ctl & ~CAPACITY 即可得到对应的线程池状态
    ctl值     :      XXX0-0000-0000-0000-0000-0000-0000-0010 
~CAPACITY值   :      1110-0000-0000-0000-0000-0000-0000-0000
-----------------------------------------------------
ctl & CAPACITY:      XXX0-0000-0000-0000-0000-0000-0000-0000
可以看出,ctl & CAPACITY 后,排除了正在执行线程个数的影响。

11. ThreadPoolExecutor 提供的状态函数

  • ThreadPoolExecutor 对外只提供 isShutdown()、 isTerminating()、isTerminated()。
  • isShutdown() 为 false 可以知道,线程池为 Running
  • 至于STOP、TIDYING 没有对外提供,可以因为没啥用吧,内部可以通过 ctl 值比较获取状态。
  • shutdown() 返回 void,shutdownNow() 会返回未执行的 list< Runnable >。
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class InstanceMethodsTest02 {
    public static void main(String[] args) throws InterruptedException {
        ThreadPoolExecutor threadPool = new ThreadPoolExecutor(1, 10,
                1L, TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue<Runnable>(1000));
        System.out.println("初始化状态,线程池是否关闭: " + threadPool.isShutdown());
        for(int i = 1; i <= 100; i++) {
            threadPool.execute(() -> {
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });
        }
        threadPool.shutdown();
        System.out.println("执行shutdown(),线程池是否关闭: " + threadPool.isShutdown());
        System.out.println("执行shutdown(),非Running,但未至终止状态: " + threadPool.isTerminating());
        System.out.println("等待一定时间后,线程池是否Terminating: " + threadPool.awaitTermination(20L, TimeUnit.SECONDS));
        System.out.println("执行shutdown(),线程池是否已经终止: " + threadPool.isTerminated());
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值