gpt4 book ai didi

java - Random 中空 for(;;) 循环的目的是什么

转载 作者:行者123 更新时间:2023-12-01 11:08:28 29 4
gpt4 key购买 nike

我正在查看 java.util.Random 类并发现了这个:

private static long seedUniquifier() {
// L'Ecuyer, "Tables of Linear Congruential Generators of
// Different Sizes and Good Lattice Structure", 1999
for (;;) {
long current = seedUniquifier.get();
long next = current * 181783497276652981L;
if (seedUniquifier.compareAndSet(current, next))
return next;
}

该循环存在有什么原因吗?

最佳答案

字段seedUniquifier是一个AtomicIntegercompareAndSet指令用于通过验证变量的预期内容和通过一次操作即可更改它。

基于Javadoc中的描述:

This constructor sets the seed of the random number generator to a value very likely to be distinct from any other invocation of this constructor.

看起来uniquifier的目的是帮助确保如果两个线程都尝试同时创建一个new Random(),它们不会都得到相同的结果种子值(以及输出序列); for 循环告诉构造函数,如果发现冲突(compareAndSet 为 false),那么它应该继续尝试。正常情况下会立即返回。

关于java - Random 中空 for(;;) 循环的目的是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32663043/

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