天天看點

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,通過這些來判斷原子性

繼續閱讀