ABA问题的解决
代码:
package com.dhy.mianshi.dhymianshi.aba; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; import java.util.concurrent.atomic.AtomicStampedReference; public class ABADemo { //ABA问题的解决 static AtomicReference<Integer> atomicReference = new AtomicReference<>(100); static AtomicStampedReference<Integer> atomicStampedReference = new AtomicStampedReference<>(100,1); // 初始值为: 100 ,版本号为: 1 public static void main(String[] args) { System.out.println("=====================以下是ABA问题的产生==================================="); new Thread(() -> { atomicReference.compareAndSet(100,101); atomicReference.compareAndSet(101,100); },"t1").start(); new Thread(() -> { //暂停1秒钟t2线程,保证上面的t1线程完成一次ABA操作 try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(atomicReference.compareAndSet(100,2019)); // 注意: 这里出现了 ABA问题 System.out.println("atomicReference.get() : "+atomicReference.get()); },"t2").start(); //暂停一会线程(确保上面的线程跑完) try { TimeUnit.SECONDS.sleep(2); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("=====================以下是ABA问题的解决==================================="); new Thread(() -> { int stamp = atomicStampedReference.getStamp(); // 获取版本号 System.out.println(Thread.currentThread().getName() + "\t第1次版本号:" + stamp); //t3线程暂停1秒钟 try {TimeUnit.SECONDS.sleep(1);} catch (InterruptedException e) {e.printStackTrace();} atomicStampedReference.compareAndSet(100,101,atomicStampedReference.getStamp(),atomicStampedReference.getStamp()+1); System.out.println(Thread.currentThread().getName() + "\t第2次版本号:" + atomicStampedReference.getStamp()); System.out.println("atomicStampedReference的值: " + atomicStampedReference.getReference()); Boolean r = atomicStampedReference.compareAndSet(101,100,atomicStampedReference.getStamp(),atomicStampedReference.getStamp()+1); System.out.println("r: " + r); System.out.println(Thread.currentThread().getName() + "\t第3次版本号:" + atomicStampedReference.getStamp()); },"t3").start(); new Thread(() -> { int stamp = atomicStampedReference.getStamp(); System.out.println(Thread.currentThread().getName() + "\t第1次版本号: " + stamp); //t4线程暂停3秒钟,能保证上面的t3线程完成一次ABA操作 try {TimeUnit.SECONDS.sleep(3); } catch (InterruptedException e) { e.printStackTrace(); } boolean result = atomicStampedReference.compareAndSet(100,2009,stamp,stamp+1); System.out.println("result :" + result); System.out.println("值 :" + atomicStampedReference.getReference()); System.out.println("版本号 :" + atomicStampedReference.getStamp()); },"t4").start(); } }
// 代码参考视频: https://haokan.baidu.com/v?pd=wisenatural&vid=5101151251744349118
posted on 2022-04-01 23:46 William_Dai 阅读(77) 评论(0) 编辑 收藏 举报