小编典典
有两个主要用途AtomicInteger:
作为incrementAndGet()可以同时被多个线程使用的原子计数器(,等)
作为支持比较和交换指令(compareAndSet())来实现非阻塞算法的原语。
这是BrianGöetz的Java Concurrency In Practice中的非阻塞随机数生成器的示例:
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())而不是增量(并在返回之前处理结果)。
2020-03-08
最后
以上就是喜悦野狼最近收集整理的关于java atomicinteger原理_Java AtomicInteger的实际用途的全部内容,更多相关java内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复