将随机数生成器与当前时间一起使用与不使用 [英] Using Random Number Generator with Current Time vs Without

查看:123
本文介绍了将随机数生成器与当前时间一起使用与不使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想了解使用以System.currentTimeMillis()作为种子的随机数生成器与仅使用默认构造函数之间的区别.也就是说,两者之间有什么区别?

I want to understand what the difference is between using a Random number generator with System.currentTimeMillis() as the seed and just using the default constructor. That is, what is the difference between this:

Random rand = new Random(System.currentTimeMillis());

和这个:

Random rand = new Random();

我知道数字是伪随机的,但是我还没有完全理解细节,以及如何得出这些数字,介于使用当前时间作为种子时的随机性"级别和默认值之间使用构造函数.

I know that the numbers are pseudo-random, but I am yet to fully understand the details, and how they come about, between the level of 'randomness' one gets when current time is used as seed, and when the default constructor is used.

推荐答案

如果希望两次运行之间的随机序列相同,则可以指定一个种子.通常,您不希望发生这种情况,因此每次运行都使用不同的种子,并且System.currentTimeMillis()是常用的合理种子.如果您面临多种情况,其中多个线程将同时初始化RNG,则可能要避免使用System.currentTimeMillis()并让Java使用其自己的初始化.

If you want your random sequences to be the same between runs you can specify a seed. Usually you don't want that to happen so you use a different seed for every run and System.currentTimeMillis() is reasonable seed commonly used. If you are facing something multithreded where multiple threads will initialize the RNG at the same time you may want to avoid using System.currentTimeMillis() and let Java use its own initialization.

这篇关于将随机数生成器与当前时间一起使用与不使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆