gpt4 book ai didi

java - 为什么 Random 中的 next 方法使用 compareAndSet?

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:41:08 24 4
gpt4 key购买 nike

在阅读 Java 中 java.util.Random 类的文档时,我偶然发现了 next 方法中的一些东西,我无法完全理解。

protected int next(int bits) {
long oldseed, nextseed;
AtomicLong seed = this.seed;
do {
oldseed = seed.get();
nextseed = (oldseed * multiplier + addend) & mask;
} while (!seed.compareAndSet(oldseed, nextseed));
return (int)(nextseed >>> (48 - bits));
}

我注意到 !seed.compareAndSet(oldseed, nextseed) 的使用,我想了解它的用途。什么解释?

最佳答案

来自 JavaDoc for compareAndSet :

Atomically sets the value to the given updated value if the current value == the expected value.

这样做是为了确保在 seed.get() 和集合(在 comapreAndSet 内)之间,没有其他线程调用另一个 set()(例如,通过并行调用 next())。因为旧的种子是用来计算下一个种子的。如果在其他线程之间调用了 seed.set() 方法,则不会使用最新值计算“下一个”种子。将使用最后一个值之前的值,并且该算法在多线程环境中会产生副作用。

该算法用于线程保存。因为如果旧值不是预期值,将重复循环直到两个值匹配。

关于java - 为什么 Random 中的 next 方法使用 compareAndSet?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33350061/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com