AtomicInteger
, and AtomicLong
extend Number
, but they're distinct from Integer
and Long
and should be handled differently. AtomicInteger
and AtomicLong
are designed to support lock-free, thread-safe programming on single variables. As such, an AtomicInteger
will only ever be "equal" to itself. Instead, you should .get()
the value and make comparisons on it.
AtomicInteger类和AtomicLong类继承自Number类,但是它们与Integer类和Long类有不同点,因此在使用上也有不同。AtomicInteger类和AtomicLong类是为支持单个变量的线程安全和无需锁定而设计的。因此,一个AtomicInteger对象的".equals()"方法比较只有在跟自己比较的时候才会返回true。所以,对于比较它们的值是否相等,就应当使用AtomicInteger对象的”.get()“方法,进行取值比较。
This applies to all the atomic, seeming-primitive wrapper classes: AtomicInteger
, AtomicLong
, and AtomicBoolean
.
这条规则适用于所有的atomic类对象,具体参考封装类:AtomicInteger,AtomicLong和AtomicBoolean
Noncompliant Code Example
AtomicInteger aInt1 = new AtomicInteger(0); AtomicInteger aInt2 = new AtomicInteger(0); if (aInt1.equals(aInt2)) { ... } // Noncompliant
Compliant Solution
AtomicInteger aInt1 = new AtomicInteger(0); AtomicInteger aInt2 = new AtomicInteger(0); if (aInt1.get() == aInt2.get()) { ... }