-4
java source code:

static {
  try {
    valueOffset = unsafe.objectFieldOffset
        (AtomicBoolean.class.getDeclaredField("value"));
  } catch (Exception ex) { throw new Error(ex); }
}

默认构造函数什么都不做:

public AtomicBoolean() {
}

变量“valueOffset”表示内存中的偏移位置?我不明白为什么它被默认构造函数初始化为'false'。我怎么能理解这个?

4

1 回答 1

2

由于默认构造函数中没有设置任何值,因此初始值是该value字段的初始化值 - 这是一个 int,没有显式值,因此它的默认值为零。

源代码

private volatile int value;

/**
 * Creates a new {@code AtomicBoolean} with the given initial value.
 *
 * @param initialValue the initial value
 */
public AtomicBoolean(boolean initialValue) {
    value = initialValue ? 1 : 0;
}

/**
 * Creates a new {@code AtomicBoolean} with initial value {@code false}.
 */
public AtomicBoolean() {
}

将其设置false为与未初始化的boolean字段一致。

于 2017-07-05T11:51:19.360 回答