Doing a = 28
(with a
being an int
) is an atomic operation. But doing a++
is not an atomic operation because it requires a read of the value of a, an incrementation, and a write to a of the result. As a result, if you used a++
to implement a thread-safe counter, you could have two threads reading the value concurrently (26 for example), then have both increment it and writing it concurrently, resulting in 27 as a result, instead of 28.
AtomicInteger solves this issue by providing atomic operations like the ones you listed. In my example, you would use incrementAndGet()
for example, which would guarantee the end value is 28 and not 27.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…