AtomicBoolean

AtomicBoolean相对AtomicInteger逻辑更简单一些,但内部仍然是用一个int型数字表示true/false状态而不是boolean变量,源码如下

成员变量

 private static final Unsafe unsafe = Unsafe.getUnsafe();
    private static final long valueOffset;

    static {
      try {
        valueOffset = unsafe.objectFieldOffset
            (AtomicBoolean.class.getDeclaredField("value"));
      } catch (Exception ex) { throw new Error(ex); }
    }
   //1 true   0 false
    private volatile int value;

构造函数

 public AtomicBoolean(boolean initialValue) {
        value = initialValue ? 1 : 0;
    }

    //这里没有设置value  因此默认初始化为0   即默认AtomicBoolean表示的是false
    public AtomicBoolean() {
    }

常用方法

 public final boolean get() {
        return value != 0;
    }

    public final boolean compareAndSet(boolean expect, boolean update) {
      //布尔变量转为 0/1 方便cas运算
        int e = expect ? 1 : 0;
        int u = update ? 1 : 0;
        return unsafe.compareAndSwapInt(this, valueOffset, e, u);
    }

    public boolean weakCompareAndSet(boolean expect, boolean update) {
        int e = expect ? 1 : 0;
        int u = update ? 1 : 0;
        return unsafe.compareAndSwapInt(this, valueOffset, e, u);
    }
    public final void set(boolean newValue) {
        value = newValue ? 1 : 0;
    }
    public final void lazySet(boolean newValue) {
        int v = newValue ? 1 : 0;
        unsafe.putOrderedInt(this, valueOffset, v);
    }
   //cas设置值
    public final boolean getAndSet(boolean newValue) {
        for (;;) {
            boolean current = get();
            if (compareAndSet(current, newValue))
                return current;
        }
    }

AtomicBoolean逻辑与AtomicInteger逻辑类似,设置值时也是for循环中算出结果,再利用UnSafe方法设置结果,

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值