分析Java线程池32位保存两个数据信息设计 (ThreadPoolExecutor 三)

代码演示

	private static final int COUNT_BITS = Integer.SIZE - 3;
    private static final int CAPACITY   = (1 << COUNT_BITS) - 1;

    // runState 用3位高字节保存多线程状态
    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;

    // workerCount 用27位低字节工作线程数量
    private static int runStateOf(int c)     { return c & ~CAPACITY; }
    private static int workerCountOf(int c)  { return c & CAPACITY; }
	
	public static void main(String[] args) {
		// 当前状态为:RUNNING,工作线程数量为:2
		int ctl = RUNNING + 2;
		
		System.out.println(runStateOf(ctl) == RUNNING);
		System.out.println(workerCountOf(ctl));
	}

运行测试类:

true
2

测试发现,变量int ctl保存了两个数据信息,那么我们来分析它是如何做到的吧。

代码分析

将数据转换为二进制

	// 29 (32-3)
	private static final int COUNT_BITS = Integer.SIZE - 3;
	// ‭00011111111111111111111111111111‬ (00100000000000000000000000000000‬ - 1)
    private static final int CAPACITY   = (1 << COUNT_BITS) - 1;
    // 11100000000000000000000000000000‬
    // ~CAPACITY;

    // runState 用3位高字节保存多线程状态
    // 11100000000000000000000000000000‬
    private static final int RUNNING    = -1 << COUNT_BITS;
    // 00000000000000000000000000000000‬
    private static final int SHUTDOWN   =  0 << COUNT_BITS;
    // 00100000000000000000000000000000‬
    private static final int STOP       =  1 << COUNT_BITS;
    // 01000000000000000000000000000000‬
    private static final int TIDYING    =  2 << COUNT_BITS;
    // 01100000000000000000000000000000‬
    private static final int TERMINATED =  3 << COUNT_BITS;

分析计算当前状态与工作线程数量方法

    private static int runStateOf(int c)     { return c & ~CAPACITY; }
    private static int workerCountOf(int c)  { return c & CAPACITY; }

实际上是分别统计高位和地位的数字
在这里插入图片描述

从上图看出

  • 线程状态有3位保存状态
  • 工作线程数量有27位保存状态

结合逻辑运算,设计的非常巧妙

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值