CAS,Compare and Swap即比较并替换。它是乐观锁思想的一种实现方式
/**
* cas 实现原理
* @Date 2022/5/9
*/
public class TestMain {
public static void main(String[] args) {
AtomicInteger atomicInteger = new AtomicInteger(0);
// 旧的预期值为0 需要修改值为1
boolean b1 = atomicInteger.compareAndSet(0, 1);
boolean b2 = atomicInteger.compareAndSet(0, 1);
System.out.println(b1+"==="+atomicInteger.get());
System.out.println(b2+"==="+atomicInteger.get());
}
}
输出:
true=1
false=1