AtomicBoolean相对AtomicInteger逻辑更简单一些,但内部仍然是用一个int型数字表示true/false状态而不是boolean变量,源码如下
成员变量
private static final Unsafe unsafe = Unsafe.getUnsafe();
private static final long valueOffset;
static {
try {
valueOffset = unsafe.objectFieldOffset
(AtomicBoolean.class.getDeclaredField("value"));
} catch (Exception ex) { throw new Error(ex); }
}
//1 true 0 false
private volatile int value;
构造函数
public AtomicBoolean(boolean initialValue) {
value = initialValue ? 1 : 0;
}
//这里没有设置value 因此默认初始化为0 即默认AtomicBoolean表示的是false
public AtomicBoolean() {
}
常用方法
public final boolean get() {
return value != 0;
}
public final boolean compareAndSet(boolean expect, boolean update) {
//布尔变量转为 0/1 方便cas运算
int e = expect ? 1 : 0;
int u = update ? 1 : 0;
return unsafe.compareAndSwapInt(this, valueOffset, e, u);
}
public boolean weakCompareAndSet(boolean expect, boolean update) {
int e = expect ? 1 : 0;
int u = update ? 1 : 0;
return unsafe.compareAndSwapInt(this, valueOffset, e, u);
}
public final void set(boolean newValue) {
value = newValue ? 1 : 0;
}
public final void lazySet(boolean newValue) {
int v = newValue ? 1 : 0;
unsafe.putOrderedInt(this, valueOffset, v);
}
//cas设置值
public final boolean getAndSet(boolean newValue) {
for (;;) {
boolean current = get();
if (compareAndSet(current, newValue))
return current;
}
}
AtomicBoolean逻辑与AtomicInteger逻辑类似,设置值时也是for循环中算出结果,再利用UnSafe方法设置结果,