CAS 版本号应用 Posted on 2021-02-13 1234567891011121314151617181920212223242526272829303132333435363738394041/** * * @author devin * @date 2021-01-08 22:11 * @version 1.0.2*/public class MyUnsafe { private static AtomicStampedReference<Integer> atomicStampedReference = new AtomicStampedReference<Integer>(100,1); public static void main(String[] args) { new Thread(() -> { System.out.println("t1拿到的初始版本号:" + atomicStampedReference.getStamp()); //睡眠1秒,是为了让t2线程也拿到同样的初始版本号 try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); } atomicStampedReference.compareAndSet(100, 101,atomicStampedReference.getStamp(),atomicStampedReference.getStamp()+1); atomicStampedReference.compareAndSet(101, 100,atomicStampedReference.getStamp(),atomicStampedReference.getStamp()+1); },"t1").start(); new Thread(() -> { //得到共享变量的版本号 int stamp = atomicStampedReference.getStamp(); System.out.println("t2拿到的初始版本号:" + stamp); //睡眠3秒,是为了让t1线程完成ABA操作 try { TimeUnit.SECONDS.sleep(3); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("最新版本号:" + atomicStampedReference.getStamp()); //确认当前值 修改值 确认版本号 赋值新的版本号 获得修改后的值 修改成功与否 System.out.println(atomicStampedReference.compareAndSet(100, 2019,3,atomicStampedReference.getStamp() + 1) + "\t当前 值:" + atomicStampedReference.getReference()); },"t2").start(); }} Donate comment here Donate WeChat Pay