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

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

CAS的ABA问题描述 AtomicStampReference

發布時間:2023/11/30 40 豆豆
生活随笔 收集整理的這篇文章主要介紹了 CAS的ABA问题描述 AtomicStampReference 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

CAS的ABA問題描述

  • 在CAS操作的時候,其他線程將當前變量的值從A改成B,又改回A;
  • CAS線程用期望值A與當前變量比較的時候,發現當前變量沒有變,于是CAS就將當前變量進行了交換操作,但其實當前變量改變過,這與設計思想是不符合的;
  • ABA問題的解決思路:每次當前變量更新的時候,將當前變量的版本號加1;

AtomicStampReference示例

  • public boolean compareAndSet(
    V expectedReference,
    V newReference,
    int expectedStamp,
    int newStamp)
    • 如果當前值和expectedReference相等,并且當前stamp和expectedStamp相等,把當前值更新為newReference,當前stamp更新為newStamp,并返回true;
    • 如果不滿足條件,不更新,并返回false;
import java.util.concurrent.TimeUnit;import java.util.concurrent.atomic.AtomicInteger;import java.util.concurrent.atomic.AtomicStampedReference;public class ABA {private static AtomicInteger atomicInt= new AtomicInteger(100);private static AtomicStampedReference atomicStampedRef= new AtomicStampedReference(100, 0);public static void main(String[] args) throws InterruptedException {Thread intABA = new Thread(new Runnable() {@Overridepublic void run() {atomicInt.compareAndSet(100, 101);atomicInt.compareAndSet(101, 100);}});Thread intCAS = new Thread(new Runnable() {@Overridepublic void run() {try {TimeUnit.SECONDS.sleep(1);} catch (InterruptedException e) {}boolean isUpdated = atomicInt.compareAndSet(100, 101);System.out.println("Thread AtomicInteger CAS isUpdated: " + isUpdated); // true}});intABA.start();intCAS.start();intABA.join();intCAS.join();Thread refABA = new Thread(() -> {try {TimeUnit.SECONDS.sleep(1);} catch (InterruptedException e) {}atomicStampedRef.compareAndSet(100, 101, atomicStampedRef.getStamp(), atomicStampedRef.getStamp() + 1);atomicStampedRef.compareAndSet(101, 100, atomicStampedRef.getStamp(), atomicStampedRef.getStamp() + 1);});Thread refCAS = new Thread(() -> {int stamp = atomicStampedRef.getStamp(); // 0try {TimeUnit.SECONDS.sleep(2);} catch (InterruptedException e) {}boolean isUpdated = atomicStampedRef.compareAndSet(100, 101, stamp, stamp + 1);System.out.println("Thread AtomicStampedReference CAS isUpdated: " + isUpdated); // false});refABA.start();refCAS.start();}}

輸出:

Thread AtomicInteger CAS isUpdated: true
Thread AtomicStampedReference CAS isUpdated: false

總結

以上是生活随笔為你收集整理的CAS的ABA问题描述 AtomicStampReference的全部內容,希望文章能夠幫你解決所遇到的問題。

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