1. AtomicInteger不是final类型,如何保证线程安全?
先看一下AtomicInteger类局部源码,关注两个字段:U以及value
public class AtomicInteger extends Number implements java.io.Serializable {
private static final long serialVersionUID = 6214790243416807050L;
/*
* This class intended to be implemented using VarHandles, but there
* are unresolved cyclic startup dependencies.
*/
private static final jdk.internal.misc.Unsafe U = jdk.internal.misc.Unsafe.getUnsafe();
private static final long VALUE = U.objectFieldOffset(AtomicInteger.class, "value");
private volatile int value;
/**
* 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}.
*/

AtomicInteger通过volatile和CAS操作确保线程安全。volatile保证value字段在多线程间的可见性,而Unsafe的compareAndSetInt方法提供原子性更新,避免额外同步措施。在多线程环境下,AtomicInteger的自增等操作安全可靠。
最低0.47元/天 解锁文章
2702

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



