重拾线程池5种状态
线程池状态分类
线程的状态具有运行与关闭的状态,那么 线程池 也不例外。java 线程池具有五种状态。
- RUNNING
- SHUTDOWN
- STOP
- TIDYING
- TERMINATED
见源码 ThreadPoolExecutor 类种的 属性
// runState is stored in the high-order bits 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;
10进制转二进制知识补充
- -1 十进制 转 二进制
- 负数 转 二进制 规则,先对绝对值转二进制,对绝对值的二进制取反再+1
1) -1 取绝对值 | - 1 | = 1 2)对十进制1 转 二进制 0001 3)对 0000 0001 取反 1110 4)取反后 加 1 1取反值 1110 1值 0001
------------------------------ 1111 5)-1 的二进制 1111
6)-1 二进制再左移 29 位 -1 << 29
1110 0000 0000 0000 0000 0000 0000 0000
-----------------------------------------
7)1 二进制左移 29 位 1 << 29
0001 0000 0000 0000 0000 0000 0000 0000
-------------------------------------------
线程池状态之间转换
线程池状态解析
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 即关闭状态,不接收新任务,但能处理已添加的任务。即等待所有的任务执行完毕。
- 当队列为空且任务全部执行完毕时,会 ShutDown 状态 ==> Tidying 状态
3、Stop
-
调用 ShutDownNow() 方法,则线程池处于 Stop 即停止状态,不接收新任务,不处理已添加的任务,并且会中断正在处理的任务。
- 当执行任务为空时,会 Stop 状态 ==> Tidying 状态。
4、Tidying
-
当所有的任务已终止,ctl记录的”任务数量”为0,线程池会变为TIDYING状态。
-
调用 terminated() 函数,TIDYING状态 ==> TERMINATED 状态。
5、Terminated
- 当线程池处于SHUTDOWN或STOP状态,并且所有⼯作线程已经销毁,任务缓存队列已经清 空或执⾏结束后,线程池被设置为TERMINATED状态。
6、线程池状态代码查验
- 线程池使用原子类 AtomicInteger ctl 存储线程状态
- 利用COUNT_BITS = 3 分割线程池状态与线程个数 (32位)
- 高位前 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()); } }