(转)Java atomic原子类的使用方法和原理(一)
在講atomic原子類之前先看一個(gè)小例子:
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; }最終的輸出結(jié)果為100,可見(jiàn)這個(gè)程序是線程安全的。如果把AtomicInteger換成變量i的話,那最終結(jié)果就不確定了。
打開(kāi)AtomicInteger的源碼可以看到:
// setup to use Unsafe.compareAndSwapInt for updates private static final Unsafe unsafe = Unsafe.getUnsafe(); private volatile int value;volatile關(guān)鍵字用來(lái)保證內(nèi)存的可見(jiàn)性(但不能保證線程安全性),線程讀的時(shí)候直接去主內(nèi)存讀,寫操作完成的時(shí)候立即把數(shù)據(jù)刷新到主內(nèi)存當(dāng)中。
CAS簡(jiǎn)要
/*** 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); }從注釋就可以看出:當(dāng)線程寫數(shù)據(jù)的時(shí)候,先對(duì)內(nèi)存中要操作的數(shù)據(jù)保留一份舊值,真正寫的時(shí)候,比較當(dāng)前的值是否和舊值相同,如果相同,則進(jìn)行寫操作。如果不同,說(shuō)明在此期間值已經(jīng)被修改過(guò),則重新嘗試。
compareAndSet使用Unsafe調(diào)用native本地方法CAS(CompareAndSet)遞增數(shù)值。
CAS利用CPU調(diào)用底層指令實(shí)現(xiàn)。
兩種方式:總線加鎖或者緩存加鎖保證原子性。
作者:zxin1
鏈接:https://www.jianshu.com/p/a2f3c46d4783
來(lái)源:簡(jiǎn)書
簡(jiǎn)書著作權(quán)歸作者所有,任何形式的轉(zhuǎn)載都請(qǐng)聯(lián)系作者獲得授權(quán)并注明出處。
轉(zhuǎn)載于:https://www.cnblogs.com/panxuejun/p/10200585.html
總結(jié)
以上是生活随笔為你收集整理的(转)Java atomic原子类的使用方法和原理(一)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 从wireshake分析http和htt
- 下一篇: 杂项:WCF