解决cas aba的问题 解决方案–AtomicStampedReference的引用加版本号

public static void main(String[] args) {//---------------------------- ABA问题解决方式AtomicStampedReference--------------------------------AtomicStampedReference<Integer> integerAtomicStampedReference=new AtomicStampedReference<>(1,1);new Thread(new Runnable() {@Overridepublic void run() {int stamp = integerAtomicStampedReference.getStamp();System.out.println("stamp:"+stamp);try {Thread.sleep(100);} catch (InterruptedException e) {e.printStackTrace();}integerAtomicStampedReference.compareAndSet(1,2,1,++stamp);integerAtomicStampedReference.compareAndSet(2,1,2,++stamp);}}).start();new Thread(new Runnable() {@Overridepublic void run() {
//                    int stamp = integerAtomicStampedReference.getStamp();
//                    System.out.println("stamp:"+stamp);try {Thread.sleep(300);} catch (InterruptedException e) {e.printStackTrace();}int stamp = integerAtomicStampedReference.getStamp();System.out.println("stamp:"+stamp);boolean compareResult = integerAtomicStampedReference.compareAndSet(1, 2, stamp, stamp+1);System.out.println("compareResult:"+compareResult);System.out.println("stamp:"+integerAtomicStampedReference.getStamp());}}).start();while (Thread.activeCount()>2){}}

本文链接:https://my.lmcjl.com/post/1571.html

展开阅读全文

4 评论

留下您的评论.