zoukankan      html  css  js  c++  java
  • AtomicInteger

    public class AtomicInteger extends Number implements java.io.Serializable {
        // setup to use Unsafe.compareAndSwapInt for updates
        private static final Unsafe unsafe = Unsafe.getUnsafe();
        private static final long valueOffset;
        
        static {
          try {
            valueOffset = unsafe.objectFieldOffset
                (AtomicInteger.class.getDeclaredField("value"));
          } catch (Exception ex) { throw new Error(ex); }
        }
        
        //使用volatile修饰,保证每次都是从主存中读取
        private volatile int value;
        
        public final int get() {
            return value;
        }
        public final void set(int newValue) {
            value = newValue;
        }
        
        //get旧值,set新值。 
        //CAS操作本来是不阻塞的,但是这里是死循环,只有当CAS返回true时,才会出循环。
        public final int getAndSet(int newValue) {
            for (;;) {
                //每次循环,都是重新get值
                int current = get();
                if (compareAndSet(current, newValue))
                    return current;
            }
        }
        
        //CAS本人,都说它是原子操作,在汇编里是一条指令。
        //首先拿到旧值,如果旧值和内存相等,并修改成功,则返回true。
        public final boolean compareAndSet(int expect, int update) {
            return unsafe.compareAndSwapInt(this, valueOffset, expect, update);
        }
    }
  • 相关阅读:
    016 vue的组件通信
    015 vue组件中的数据
    014 vue的组件化开发
    013 vue的js中的高阶函数
    012 vue的v-model的使用
    011 vue的购书案例
    010 vue的过滤器的使用
    CF1519F
    CF1519E
    CF1517F
  • 原文地址:https://www.cnblogs.com/allenwas3/p/8401360.html
Copyright © 2011-2022 走看看