天天看点

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(*l);
                    } 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();
                } 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 ?  : ;
    }
           

然后:

public final boolean compareAndSet(boolean expect, boolean update) {
        int e = expect ?  : ;
        int u = update ?  : ;
        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,通过这些来判断原子性

继续阅读