AtomicInteger,由于存储的值的value是volatile类型所有具有线程可见性。通过CAS比较交换进行自增,或者更新值具有原子性。所以AtomicInteger是线程安全的具有类锁一样的线程安全性。
具体参见下面源码解析:
private static final Unsafe unsafe = Unsafe.getUnsafe();
private static final long valueOffset;
static {
try {
valueOffset = unsafe.objectFieldOffset
(AtomicInteger.class.getDeclaredField("value"));
} catch (Exception ex) { throw new Error(ex); }
}
private volatile int value;//volatile保证了多线程之间的内存可见性
/**
* Creates a new AtomicInteger with the given initial value.
*
* @param initialValue the initial value
*/
public AtomicInteger(int initialValue) {
value = initialValue;
}
/**
* Creates a new AtomicInteger with initial value {@code 0}.
*/
public AtomicInteger() {
}
//expect预期原值,update更新值,如果预期值等于原值,用更新值替换原值。替换成功返回true,否则返回false.具有volatile的读写内存语义。
public final boolean compareAndSet(int expect, int update) {
return unsafe.compareAndSwapInt(this, valueOffset, expect, update);
}
public final int incrementAndGet() {
for (;;) {
int current = get();
int next = current + 1;
if (compareAndSet(current, next))
return next;
}
}
public final int decrementAndGet() {
for (;;) {
int current = get();
int next = current - 1;
if (compareAndSet(current, next))
return next;
}
}
AtomicInteger原理与应用

本文详细介绍了AtomicInteger类的工作原理及其实现线程安全的方法。AtomicInteger利用了Unsafe类提供的compareAndSwapInt方法来实现CAS操作,从而确保了自增和自减等操作的原子性。此外,还通过volatile关键字保证了多线程环境下变量修改的可见性。
1万+

被折叠的 条评论
为什么被折叠?



