正确代码详解:
public class AtomicStampedReferenceTest {
private final static AtomicStampedReference<Integer> atomicStampedReference = new AtomicStampedReference<>(100, 1);
public static void main(String[] args) {
new Thread(() -> {
int stamp = atomicStampedReference.getStamp();
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + " 第1次版本号:" + stamp);
boolean c = atomicStampedReference.compareAndSet(100, 101, atomicStampedReference.getStamp(), atomicStampedReference.getStamp() + 1);
System.out.println(Thread.currentThread().getName() + " 第2次版本号:" + atomicStampedReference.getStamp()+" boolean:"+c);
boolean b = atomicStampedReference.compareAndSet(101, 100, atomicStampedReference.getStamp(), atomicStampedReference.getStamp() + 1);
System.out.println(Thread.currentThread().getName() + " 第2次版本号:" + atomicStampedReference.getStamp()+" boolean:"+b);
}).start();
new Thread(() -> {
int stamp = atomicStampedReference.getStamp();
try {
TimeUnit.SECONDS.sleep(3);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + " 第1次版本号:" + stamp);
boolean b = atomicStampedReference.compareAndSet(100, 2021, stamp, stamp + 1);
System.out.println(Thread.currentThread().getName() + " 获取到的值:" + atomicStampedReference.getReference() + " boolean:"+b);
}).start();
}
}
AtomicStampedReference源码分析欢迎大家搜索“小猴子的技术笔记”关注我的公众号,领取更多学习资料。有问题可以及时和我交流。 之前的文章已经介绍过CAS的操作原理,它虽然能够保证数据的原子性,...