zoukankan      html  css  js  c++  java
  • AtomicI 多线程中的原子操作

    原子类的工具类包含下面:

    常涉及到的方法:compareAndSet();  先对比,后赋值,

    举例  AtomicInteger :

                     AtomicInteger i = new AtomicInteger();
    		 i.set(1);
    		 i.compareAndSet(2,3);//用2和1对比,返回false,所以不赋值
    		 System.out.println(i.get());//结果:1
    		 i.compareAndSet(1,3);//用1和1对比,返回true,然后进行赋值
    		 System.out.println(i.get());//结果:3        
    

      

    内部实现:

    public class AtomicInteger extends Number implements java.io.Serializable {
        private static final long serialVersionUID = 6214790243416807050L;
    
        // 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); }
        }
    
        private volatile int value;
    
        /**
         * Creates a new AtomicInteger with the given initial value.
         *
         * @param initialValue the initial value
         */
        public AtomicInteger(int initialValue) {
            value = initialValue;
        }
    

      是使用volatile作为关键字实现的

  • 相关阅读:
    108.异常的传递
    107.捕获异常
    106.异常、模块(异常介绍)
    105.面向对象案例-烤红薯
    104.多态案例
    103.继承案例二
    102.继承案例一
    101.自定义玩家类
    100.自定义枪类
    python基础入门之十四 —— 文件操作
  • 原文地址:https://www.cnblogs.com/sg9527/p/7693352.html
Copyright © 2011-2022 走看看