Java 7:ThreadLocalRandom生成相同的随机数

dog*_*ane 14 java random java-7

我正在尝试使用Java 7的 ThreadLocalRandom,并发现它在多个线程中生成完全相同的随机数.

这是我的代码,我创建了5个线程,每个线程打印出5个随机数:

//5 threads
for(int i = 0; i < 5 ; i++) {
    final Thread thread = new Thread() {
        @Override
        public void run() {
            System.out.print(Thread.currentThread().getName()+":");

            //each thread prints 5 random numbers
            for(int j = 0 ; j < 5; j++) {
                final int random = ThreadLocalRandom.current().nextInt(1,100);
                System.out.print(random + ",");
            }
            System.out.println();
        }
    };
    thread.start();
    thread.join();
}
Run Code Online (Sandbox Code Playgroud)

输出:

Thread-0:1,93,45,75,29,
Thread-1:1,93,45,75,29,
Thread-2:1,93,45,75,29,
Thread-3:1,93,45,75,29,
Thread-4:1,93,45,75,29,
Run Code Online (Sandbox Code Playgroud)

为什么我为每个线程和每次执行程序获得相同的随机数?

MBy*_*ByD 11

似乎有一个关于这个问题的公开错误.看到这里这里

  • 该错误已在JDK7的Update 2中得到解决.在此下载:http://www.oracle.com/technetwork/java/javase/downloads/jdk-7u2-download-1377129.html (2认同)

rat*_*eak 5

谷歌搜索"ThreadLocalRandom源"给了我http://www.assembla.com/code/scala-eclipse-toolchain/git/nodes/src/forkjoin/scala/concurrent/forkjoin/ThreadLocalRandom.java

它的长/短:它使用一个ThreadLocal<ThreadLocalRandom>调用no-arg构造函数来构造

no-arg构造函数是

/**
 * Constructor called only by localRandom.initialValue.
 * We rely on the fact that the superclass no-arg constructor
 * invokes setSeed exactly once to initialize.
 */
ThreadLocalRandom() {
    super();
}
Run Code Online (Sandbox Code Playgroud)

Random中的no-arg super 使用唯一种子调用this(long)

不过那个构造函数呢

public Random(long seed) {
    this.seed = new AtomicLong(initialScramble(seed));
}
Run Code Online (Sandbox Code Playgroud)

即不是文档的预期行为

和ThreadLocalRandom没有/不能使用私有 seed