首页 > 其他 > 详细

AtomicInteger的Increment方法的自己实现。

时间:2020-03-20 23:04:23      阅读:88      评论:0      收藏:0      [点我收藏+]
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加一
    }
}

 

AtomicInteger的Increment方法的自己实现。

原文:https://www.cnblogs.com/Esquecer/p/12535123.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!