首页 > 其他分享 >ThreadPoolExecutor

ThreadPoolExecutor

时间:2023-01-20 16:57:15浏览次数:46  
标签:11111111 策略 00000000 线程 ctl ThreadPoolExecutor

1. ThreadPoolExecutor核心参数

image


2. RejectedExecutionHandler —— 拒绝策略

1. AbortPolicy--中止策略

image

使用该策略时,直接抛出一个RejectedExecutionException异常


2. DiscardPolicy--不理睬策略

image

使用该策略时,什么也不做,会影响要执行的该任务


3. DiscardOldestPolicy--丢弃队头策略

image

· 使用该策略时,会先获取阻塞队列,然后从阻塞队列中将队头任务出队,再尝试执行该任务


4. CallerRunsPolicy

image

使用该策略时,当线程池没有空闲处理该任务时,调用execute的主线程会执行该任务;该策略会对主线程造成较大影响,也可以给线程池做一个缓冲。

3. 线程池的执行流程

image

  1. 源码分析

image
image


4.线程池ctl属性

点击查看代码
    // ctl本质上就是一个int类型的数值,
    private final AtomicInteger ctl = new AtomicInteger(ctlOf(RUNNING, 0));
    // Integer.SIZE = 32bit  ,COUNT_BITS = 29
    // ctl表述了两个状态
    // (1) 表述了线程池当前的状态(高3位用于表示线程池状态)
    // (2) 表述了线程池的当前工作线程的个数(低29位表示)
    private static final int COUNT_BITS = Integer.SIZE - 3;
    // 00000000  00000000  00000000  00000001 ==>  00100000  00000000  00000000  00000000
    // 00100000  00000000  00000000  00000000 - 1 = 00011111 11111111  11111111  11111111
    // 00011111 11111111  11111111  11111111 = 1FFF FFFFH
    // 表述了工作线程的最大数量(包括核心线程和非核心线程)
    private static final int COUNT_MASK = (1 << COUNT_BITS) - 1;

    // 线程池的五种状态
    // 通过高3位表示线程状态
    // runState is stored in the high-order bits
    // 运行状态
    // -1 = 11111111 11111111 11111111B
    // 往左移动29位后
    // 11100000 00000000 00000000B
    private static final int RUNNING    = -1 << COUNT_BITS;
    // 00000000 00000000 00000000
    private static final int SHUTDOWN   =  0 << COUNT_BITS;
    // 001
    private static final int STOP       =  1 << COUNT_BITS;
    // 010
    private static final int TIDYING    =  2 << COUNT_BITS;
    // 011
    private static final int TERMINATED =  3 << COUNT_BITS;

    // Packing and unpacking ctl
    // 计算出当前线程池的状态
    // 00011111 11111111  11111111  11111111
    // 11100000 00000000  00000000  00000000
    // 相与
    // 000 00000 00000000 00000000 00000000
    private static int runStateOf(int c)     { return c & ~COUNT_MASK; }
    // 计算出当前线程池中的工作线程的个数
    private static int workerCountOf(int c)  { return c & COUNT_MASK; }

5.线程池的状态转换

image

标签:11111111,策略,00000000,线程,ctl,ThreadPoolExecutor
From: https://www.cnblogs.com/lsh-admin/p/17037165.html

相关文章