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

Why does the next method in Random use a compareAndSet?

在阅读 Java 中 java.util.Random class 的文档时,我偶然发现了 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() 方法,则不会使用最新值计算 "next" 种子。将使用最后一个值之前的值,并且该算法将在多线程环境中产生副作用。

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