1.什么是CAS
public class CasDemo {
public static void main(String[] args) {
AtomicInteger atomicInteger = new AtomicInteger(2020);
atomicInteger.compareAndSet(2020,2021);
atomicInteger.getAndIncrement();
System.out.println(atomicInteger.get());
}
}
2.ABA问题
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/08844d98115e16674aa645c9ce7422cd.png)
public class CasDemo2 {
public static void main(String[] args) {
AtomicStampedReference<Integer> atomicStampedReference = new AtomicStampedReference(1,1);
new Thread(()->{
atomicStampedReference.compareAndSet(
1, 3, atomicStampedReference.getStamp(),
atomicStampedReference.getStamp()+1
);
System.out.println(Thread.currentThread().getName()+" "+atomicStampedReference.getStamp());
System.out.println(Thread.currentThread().getName()+" int "+atomicStampedReference.getReference());
atomicStampedReference.compareAndSet(
3, 1, atomicStampedReference.getStamp(),
atomicStampedReference.getStamp()+1
);
System.out.println(Thread.currentThread().getName()+" "+atomicStampedReference.getStamp());
System.out.println(Thread.currentThread().getName()+" int "+atomicStampedReference.getReference());
},"A").start();
new Thread(()->{
try {
TimeUnit.SECONDS.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
}
atomicStampedReference.compareAndSet(
1, 2, atomicStampedReference.getStamp(),
atomicStampedReference.getStamp()+1
);
System.out.println(Thread.currentThread().getName()+" "+atomicStampedReference.getStamp());
System.out.println(Thread.currentThread().getName()+" int "+atomicStampedReference.getReference());
},"B").start();
}
}