日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > java >内容正文

java

atomic原子类实现机制_深入了解Java atomic原子类的使用方法和原理

發布時間:2023/12/15 java 26 豆豆
生活随笔 收集整理的這篇文章主要介紹了 atomic原子类实现机制_深入了解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;

volatile關鍵字用來保證內存的可見性(但不能保證線程安全性),線程讀的時候直接去主內存讀,寫操作完成的時候立即把數據刷新到主內存當中。

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);

}

從注釋就可以看出:當線程寫數據的時候,先對內存中要操作的數據保留一份舊值,真正寫的時候,比較當前的值是否和舊值相同,如果相同,則進行寫操作。如果不同,說明在此期間值已經被修改過,則重新嘗試。

compareAndSet使用Unsafe調用native本地方法CAS(CompareAndSet)遞增數值。

CAS利用CPU調用底層指令實現。

兩種方式:總線加鎖或者緩存加鎖保證原子性。

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持我們。

時間: 2019-06-22

總結

以上是生活随笔為你收集整理的atomic原子类实现机制_深入了解Java atomic原子类的使用方法和原理的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。