public class AtomicBoolean implements java.io.Serializable
一:作用
A boolean value that may be updated atomically
二:主要成员变量
private static final Unsafe unsafe = Unsafe.getUnsafe();
sun 提供进行一些非安全操作的类
private static final long valueOffset;
保存value属性在这个对象中内存位置的偏移量,unsafe对象中会使用该值
private volatile int value;
保存该对象的值,如果为true则value = 1 ,如果为false则value = 0;
volatile表示在多线程的情况下,如果有线程在修改这个属性值,则别的线程读取该属性的值一定是修改完成后的值,保证了可见性
三:主要成员方法
获得值
/**
* Returns the current value.
*
* @return the current value
*/
public final boolean get() {
return value != 0;
}
比较和替换
/**
* 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 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);
}
设置值
/**
* Unconditionally sets to the given value.
*
* @param newValue the new value
*/
public final void set(boolean newValue) {
value = newValue ? 1 : 0;
}
获得并设置新值
/**
* 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) {
for (;;) {
boolean current = get();
if (compareAndSet(current, newValue))
return current;
}
}