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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章