常见的原子类:
- 基本类:
AtomicInteger、AtomicLong、AtomicBoolean; - 引用类型:
AtomicReference、AtomicReference的ABA实例、AtomicStampedRerence、AtomicMarkableReference; - 数组类型:
AtomicIntegerArray、AtomicLongArray、AtomicReferenceArray - 属性原子修改器(Updater):
AtomicIntegerFieldUpdater、AtomicLongFieldUpdater、AtomicReferenceFieldUpdater
本节介绍:AtomicBoolean类
1.首先维护了一个volatile的value,保证线程可见
private volatile int value;
2.get方法
public final boolean get() {
return value != 0;
}
3.getAndSet
/**
* Atomically sets to the given value and returns the previous value.
*
* @param newValue the new value
* @return the previous value
*/
public final boolean getAndSet(boolean newValue) {
boolean prev;
do {
prev = get();
} while (!compareAndSet(prev, newValue));
return prev;
}
4.compareAndSet
/**
* Atomically sets the value to the given updated value
* if the current value {@code ==} the expected value.
*
* @param expect the expected value
* @param update the new value
* @return {@code true} if successful. False return indicates that
* the actual value was not equal to the expected value.
*/
public final boolean compareAndSet(boolean expect, boolean update) {
int e = expect ? 1 : 0;
int u = update ? 1 : 0;
return unsafe.compareAndSwapInt(this, valueOffset, e, u);
}
5.set
/**
* Unconditionally sets to the given value.
*
* @param newValue the new value
*/
public final void set(boolean newValue) {
value = newValue ? 1 : 0;
}
由此可见,原子类底层使用的是unsafe类的CAS来控制原子操作的,如果CAS失败则一直尝试。而且value使用volatile保证多线程可见性。