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

2022-09-03 14:29:11

我正在尝试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();
}

输出:

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,

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


答案 1

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


答案 2

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

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

无参数构造函数是

/**
 * 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();
}

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

但是,该构造函数确实

public Random(long seed) {
    this.seed = new AtomicLong(initialScramble(seed));
}

即不是文档中的预期行为

和 ThreadLocalRandom 不/不能使用私有seed


推荐