以下代码应创建两个具有相同种子的Random对象:
System.out.println("System time before: " + System.currentTimeMillis());
Random r1 = new Random();
Random r2 = new Random(System.currentTimeMillis());
System.out.println("System time after: " + System.currentTimeMillis());
System.out.println("r1: " + r1.nextInt());
System.out.println("r2: " + r2.nextInt());
Run Code Online (Sandbox Code Playgroud)
种子应该是相同的,因为System.currentTimeMillis()在创建两个对象之前和之后没有变化,如输出中所示:
System time before: 1331889186449
System time after: 1331889186449
r1: -1836225474
r2: 2070673752
Run Code Online (Sandbox Code Playgroud)
从文档中,没有任何参数的构造函数只是:
public Random() { this(System.currentTimeMillis()); }
Run Code Online (Sandbox Code Playgroud)
什么给出了什么?任何人都可以解释为什么两个发电机应该有相同的种子时会返回不同的输出?
如果您使用的是java.util.Random,这是我看到的默认的no-args构造函数 - 现在它可能取决于您使用的JDK版本(此代码似乎至少用于sun JDK 6和7):
public Random() {
this(seedUniquifier() ^ System.nanoTime());
}
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;
}
}
Run Code Online (Sandbox Code Playgroud)
只是为了确认它,这里有一个代码来检查种子是否相同:
public static void main(String args[]) throws NoSuchFieldException, IllegalArgumentException, IllegalAccessException {
System.out.println("System time before: " + System.currentTimeMillis());
Random r1 = new Random();
Random r2 = new Random(System.currentTimeMillis());
System.out.println("System time after: " + System.currentTimeMillis());
Field seed = Random.class.getDeclaredField("seed");
seed.setAccessible(true);
AtomicLong seed1 = (AtomicLong) seed.get(r1);
AtomicLong seed2 = (AtomicLong) seed.get(r2);
System.out.println("seed1 = " + seed1);
System.out.println("seed2 = " + seed2);
}
Run Code Online (Sandbox Code Playgroud)