atomicBoolean 用法根据部分源码看

今天小G,说下AtomicBoolean,使用该方法进行原子操作,

package test;

import java.util.concurrent.atomic.AtomicBoolean;

import sun.util.logging.resources.logging_ko;

public class c{
    public final static AtomicBoolean atomicBoolean=new AtomicBoolean(false);
    public static void main(String[] args) {
        System.out.println("测试一开始");

        new Thread(new Runnable() {

            @Override
            public void run() {

                if(atomicBoolean.compareAndSet(false, true)) {
                    System.out.println("线程开始等待");
                    try {
                        Thread.sleep(5*1000l);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();        
                    }
                    System.out.println("线程开始解锁");
                    atomicBoolean.set(false);
                    System.out.println("线程结束");
                    if(atomicBoolean.compareAndSet(false, true)) {
                        System.out.println("线程再次进入");
                    }
                }
            }
        }).start();
       new Thread(new Runnable() {

            @Override
            public void run() {
            try {
                    System.out.println("线程2开始进入");
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                if(atomicBoolean.compareAndSet(false, true)) {
                    System.out.println("线程2开始进入");
                }
            }
        }).start();


    }

}

输出结果为:

测试一开始
线程开始等待
线程2开始进入
线程开始解锁
线程结束
线程再次进入

看下源码:
首先看下

    private volatile int value;
    /**
     * Creates a new {@code AtomicBoolean} with the given initial value.
     *
     * @param initialValue the initial value
     */
    public AtomicBoolean(boolean initialValue) {
        value = initialValue ? 1 : 0;
    }

然后:

    public final boolean compareAndSet(boolean expect, boolean update) {
        int e = expect ? 1 : 0;
        int u = update ? 1 : 0;
        return unsafe.compareAndSwapInt(this, valueOffset, e, u);
    }

其中compareAndSwapInt方法大家可以看下https://www.cnblogs.com/snowater/p/8303698.html ,这里面其实,就是进行比对,e表示预期值和u修改值,如果不是就返回false,这样就控制原子性质,其中大家有没有看到,value使用的 private volatile int value; 使用的是volatile可见性,多线程进行比对,是否原始的值,如是原始的值发生变化,不是原始的值,那么就返回false,通过这些来判断原子性

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值