AtomicInteger的Increment方法的自己实现。

package demo01;

import sun.misc.Unsafe;

import java.lang.reflect.Field;

public class testUnsafe {

    static final Unsafe unsafe;
    static final  long offset;
    private  volatile long state = 0;
    static {
        try{
            //暴力反射获得值,不然会报错
            Field filed = Unsafe.class.getDeclaredField("theUnsafe");
            filed.setAccessible(true);
            unsafe = (Unsafe)filed.get(null);

            Field state1 = testUnsafe.class.getDeclaredField("state");
            offset = unsafe.objectFieldOffset(state1);
        }catch (Exception e){
            e.printStackTrace();
            throw  new Error();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        testUnsafe tu = new testUnsafe();
        /*
        //改变结果 0 变成 1
        boolean b = unsafe.compareAndSwapInt(tu, offset, 0, 1);
        int intVolatile = unsafe.getIntVolatile(tu, offset);
        System.out.println(b + "  值是: "+intVolatile);

        //cas操作失败,因为当前内存的值是1不是2 (比较第三个参数)
        b = unsafe.compareAndSwapInt(tu, offset, 2, 1);
        intVolatile = unsafe.getIntVolatile(tu, offset);
        System.out.println(b + "  值是: "+intVolatile);
        */
        for(int i = 0 ; i < 10 ; i ++){
            new Thread(()->{
                for(int j = 0 ; j < 10000 ; j ++){
                    increment(tu,offset);
                }
            }).start();
        }
        Thread.sleep(1000);
        System.out.println(tu.state);
    }

    //自己的AtomicInteger的increment方法
    public static void increment(Object o,long offset){
        int oldVal = 1;
        // CAS来实现,比较oldVal
        do{
            //获得原来的值
           oldVal = unsafe.getIntVolatile(o, offset);
        }while(!unsafe.compareAndSwapInt(o,offset,oldVal,oldVal+1));//oldval加一
    }
}

 

上一篇:初识vue02


下一篇:vue/cli3 + typescript 中watch prop component computed 的用法