java - java中随机数生成器详解

标签 java random

阅读关于 Fisher-Yates 的维基百科页面,将最后一段打乱是:

Finally, it is to be noted that even with perfect random number generation, flaws can be introduced into an implementation by improper usage of the generator. For example, suppose a Java implementation creates a new generator for each call to the shuffler, without passing constructor arguments. The generator will then be default-seeded by the language's time-of-day (System.currentTimeMillis() in the case of Java). So if two callers call the shuffler within a time-span less than the granularity of the clock (one millisecond in the case of Java), the generators they create will be identical, and (for arrays of the same length) the same permutation will be generated. This is almost certain to happen if the shuffler is called many times in rapid succession, leading to an extremely non-uniform distribution in such cases; it can also apply to independent calls from different threads. A more robust Java implementation would use a single static instance of the generator defined outside the shuffler function.

除了这一段的最后一句,我什么都懂。作者说:

A more robust Java implementation would use a single static instance of the generator defined outside the shuffler function.?

最佳答案

这意味着你有一个像这样的静态函数:

class RandomUtil {

    public static final Random rand = new Random();     

}

然后您使用此随机数生成器 RandomUtil.rand.nextInt() 生成您所有的随机数。您只使用这一个实例,并确保不会出现维基中提到的问题。

关于java - java中随机数生成器详解,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11323245/

相关文章:

java - 我的程序出了什么问题?它没有显示任何时钟计时器?

java - Veracode 问题 - 通过发送的数据暴露信息 (CWE ID 201)

c - 我试图将随机整数分配给结构成员,但它无法正常工作

java - 为什么允许在 Java 中标记几乎所有语句?

在获得文件锁定之前,Java5 FileInputStream 失败

matlab - 在 matlab 中使用 rand 生成限制之间的数字

Ruby//range之间的随机数,保证对其他已有存储的唯一性

iphone - 在 cocos2d 中使用 NSTimer 制作随机对象

java - Spring @Transactional(readOnly=true) 恢复属性?

java - 如何在 Clojure 中实现全包随机数函数?