java.util
java.lang.Object
? java.util.Random
两种构造器:
源码:
public Random() {
this(seedUniquifier() ^ System.nanoTime());
}
public Random(long seed) {
if (getClass() == Random.class)
this.seed = new AtomicLong(initialScramble(seed));
else {
// subclass might have overriden setSeed
this.seed = new AtomicLong();
setSeed(seed);
}
}
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));
}
关于System.nanoTime():
输出精度是纳秒,对比System.currentTime()输出的精度是毫秒,返回值是1970.1.1的零点开始到当前时间的毫秒数。但System.nanoTime()不同,代码注释:The value returned reprensents nonoseconds since some fixed but arbitary time(perhaps in the future, so values may be negative),即有可能从未来算起,返回负值
所以System.nanoTime()方法只能用来计时,例如:
long s = System.nanoTime();
//do something
System.out.println(System.nanoTime() - s);
采用Random(),每次会随机出一系列不同的数字
而采用Random(long seed),产生的实际是伪随机数,是固定的一系列数字
参考博文:https://blog.csdn.net/u010746357/article/details/105642771?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-3.channel_param&depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-3.channel_param
https://blog.csdn.net/yuansuruanjian/article/details/8562890
原文:https://www.cnblogs.com/Glov/p/13456932.html