CAS

package com.example.test.thread;

import sun.misc.Unsafe;

import java.lang.reflect.Field;
import java.util.concurrent.TimeUnit;

public class LockCas {

    volatile int value=0;
    private static Long valueOfSet;
    private static Unsafe unsafe;

    static{
        try {
            Field filed =  Unsafe.class.getDeclaredField("theUnsafe");
            filed.setAccessible(true);
            unsafe = (Unsafe) filed.get(null);
            valueOfSet = unsafe.objectFieldOffset(LockCas.class
                    .getDeclaredField("value"));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void add(){
        int current;
        do {
            current = unsafe.getIntVolatile(this,valueOfSet);
        }while (!unsafe.compareAndSwapInt(this,valueOfSet,current,current+1));

    }


    public static void main(String[] args) throws InterruptedException {
        LockCas lockCas = new LockCas();
        for (int i = 0; i <2 ; i++) {
            new Thread(()->{
                for(int j=0;j<10000;j++){
                    lockCas.add();
                }
            }).start();
        }
        TimeUnit.SECONDS.sleep(2);
        System.out.println(lockCas.value);
    }


}

 

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