问题描述
我有点理解 AtomicInteger 和其他 Atomic 变量允许并发访问.在什么情况下通常使用这个类?
I sort of understand that AtomicInteger and other Atomic variables allow concurrent accesses. In what cases is this class typically used though?
推荐答案
AtomicInteger
主要有两个用途:
作为一个原子计数器(
incrementAndGet()
等),可以被多个线程同时使用
As an atomic counter (
incrementAndGet()
, etc) that can be used by many threads concurrently
作为支持 compare-and-swap 指令的原语(compareAndSet()
) 来实现非阻塞算法.
As a primitive that supports compare-and-swap instruction (compareAndSet()
) to implement non-blocking algorithms.
以下是来自 的非阻塞随机数生成器示例Brian Göetz 的 Java 并发实践:
public class AtomicPseudoRandom extends PseudoRandom {
private AtomicInteger seed;
AtomicPseudoRandom(int seed) {
this.seed = new AtomicInteger(seed);
}
public int nextInt(int n) {
while (true) {
int s = seed.get();
int nextSeed = calculateNext(s);
if (seed.compareAndSet(s, nextSeed)) {
int remainder = s % n;
return remainder > 0 ? remainder : remainder + n;
}
}
}
...
}
如您所见,它的工作方式与 incrementAndGet()
基本相同,但执行任意计算(calculateNext()
)而不是增量(并处理返回前的结果).
As you can see, it basically works almost the same way as incrementAndGet()
, but performs arbitrary calculation (calculateNext()
) instead of increment (and processes the result before return).
这篇关于AtomicInteger 的实际用途的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!