AtomicInteger

作用:可用原子方式更新的 int 值
public class AtomicInteger extends Number implements java.io.Serializable {
	private static final long serialVersionUID = 6214790243416807050L;

	// Unsafe类使Java拥有了像C语言的指针一样操作内存空间的能力
	private static final Unsafe unsafe = Unsafe.getUnsafe();
	// 记录value字段相对于对象的起始内存地址的字节偏移量,主要是为了在更新操作在内存中找到value的位置,方便比较。
	private static final long valueOffset;

	private volatile int value;

	static {
		try 
		{
			// 获取value字段相对于对象的起始内存地址的字节偏移量
			valueOffset = unsafe.objectFieldOffset(AtomicInteger.class.getDeclaredField("value"));
		} catch (Exception ex) {
			throw new Error(ex);
		}

	}
	
	// 使用unsafe的native方法,实现高效的硬件级别CAS
	public final int incrementAndGet() {
		return unsafe.getAndAddInt(this, valueOffset, 1) + 1;
	}
}

你可能感兴趣的:(JAVA并发基础类库)