AtomicInteger的get()vs intValue()

Saa*_*aad 6 java atomicity

为什么AtomicInteger同时具有int get()和int intValue()?我看到它还有来自Number的float floatValue().是否有一个与维持AtomicInteger参数的原子性相关的含义,或者是否可以互换?

rge*_*man 7

它们应该是可以互换的.以下是源代码的相关部分AtomicInteger:

public int intValue() {
    return get();
}
Run Code Online (Sandbox Code Playgroud)

  • 这不是真的。得到是最终的。intValue 不是最终的。 (2认同)

Sre*_*hat 6

intValue 定义:

/**
 * Returns the value of this {@code AtomicInteger} as an {@code int}.
 */
public int intValue() {
    return get();
}
Run Code Online (Sandbox Code Playgroud)

get 定义:

/**
 * Gets the current value.
 *
 * @return the current value
 */
public final int get() {
    return value;
}
Run Code Online (Sandbox Code Playgroud)

您可以清楚地看到该get方法是final. final方法不能被覆盖。

如果我们扩展 AtomicInteger 类,我们不能覆盖该get方法,但我们可以覆盖该intValue方法。