关于CAS(CompareAndSet)

import java.util.concurrent.atomic.AtomicInteger;

public class CasDemo {
//CAS: CompareAndSet 比较并交换
public static void main(String[] args) {
AtomicInteger atomicInteger = new AtomicInteger(2020);
//期望、更新
//public final boolean compareAndSet(int expect, int update)
//如果期望的值达到了就更新,否则就不更新
System.out.println(atomicInteger.compareAndSet(2020, 2021));
System.out.println(atomicInteger.get());


System.out.println(atomicInteger.compareAndSet(2020, 2021));
System.out.println(atomicInteger.get());
}
}

/*
CAS缺点:
1、循环会耗时
2、一次性只能保证一个共享变量的原子性
3、ABA问题
*/
posted @ 2021-08-06 17:33  gdstcymc  阅读(43)  评论(0)    收藏  举报