这两天花了点时间看AtomicInteger,再为这个管理器设置值时用到了compareAndSet方法,有点些许难理解,首先在AtomicInteger内部,有个value变量,
private volatile int value; volatile保证变量的线程间可见性,compareAndSet方法实际上是做了两部操作,第一是比较
public final boolean compareAndSet(int expect, int update);value的值为expect的值,第二是把value的值更新为
update,这两步是原子操作,在没有多线程锁的情况下,借助cpu锁保证数据安全。