zoukankan      html  css  js  c++  java
  • 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加一
        }
    }
  • 相关阅读:
    待解决的问题
    Java编译环境的搭建(eclipse)
    Ubuntu升级没有声音的解决方法
    Ubuntu中文输入法的添加
    apue和error
    韦东山linux学习之ubuntu 9.10 软件源 问题
    查询表的列名
    事务管理
    数组 String[]
    java 内存
  • 原文地址:https://www.cnblogs.com/Esquecer/p/12535123.html
Copyright © 2011-2022 走看看