天天看點

(轉)Java atomic原子類的使用方法和原理(一)

在講atomic原子類之前先看一個小例子:

public class UseAtomic {
   
   public static void main(String[] args) {
       AtomicInteger atomicInteger=new AtomicInteger();
       for(int i=0;i<10;i++){
            Thread t=new Thread(new AtomicTest(atomicInteger));
            t.start();
            try {
               t.join(0);
           } catch (InterruptedException e) {
               e.printStackTrace();
           }
               
       }
       System.out.println(atomicInteger.get());
   }
}
class AtomicTest implements Runnable{
   AtomicInteger atomicInteger;
   
   public AtomicTest(AtomicInteger atomicInteger){
       this.atomicInteger=atomicInteger;
   }
   @Override
   public void run() {
       atomicInteger.addAndGet(1);
       atomicInteger.addAndGet(2);
       atomicInteger.addAndGet(3);
       atomicInteger.addAndGet(4);
   }
   
}
           

最終的輸出結果為100,可見這個程式是線程安全的。如果把AtomicInteger換成變量i的話,那最終結果就不确定了。

打開AtomicInteger的源碼可以看到:

// setup to use Unsafe.compareAndSwapInt for updates
private static final Unsafe unsafe = Unsafe.getUnsafe();
           
private volatile int value;
           

CAS簡要

/**
     * Atomically sets the value to the given updated value
     * if the current value {@code ==} the expected value.
     *
     * @param expect the expected value
     * @param update the new value
     * @return {@code true} if successful. False return indicates that
     * the actual value was not equal to the expected value.
     */
    public final boolean compareAndSet(int expect, int update) {
        return unsafe.compareAndSwapInt(this, valueOffset, expect, update);
    }
           

作者:zxin1

連結:https://www.jianshu.com/p/a2f3c46d4783

來源:簡書

簡書著作權歸作者所有,任何形式的轉載都請聯系作者獲得授權并注明出處。

繼續閱讀