AtomicBoolean跟AtomicInteger都有一个compareAndSet的方法
public final boolean compareAndSet(boolean expect, boolean update)
public final boolean compareAndSet(int expect, int update)
我网上看见compareAndSet的应用可以是防止多次初始化,比如多个线程想用compareAndSet来判断是否初始化过,只有一个线程能初始化
public final boolean getAndSet(boolean newValue) {
for (;;) {
boolean current = get();
if (compareAndSet(current, newValue))
return current;
}
}
当然AtomicBoolean最重要的就是getAndSet可以保证多个线程原子的更新值,可以看见代码是不停的检查,如果符合期望值就可以更新
public final int getAndIncrement() {
for (;;) {
int current = get();
int next = current + 1;
if (compareAndSet(current, next))
return current;
}
}
AtomicInteger可以保证多个线程原子的加1,可以当计数器用。代码里不停的用checkAndSet来实现。