我正在试用 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,
为什么每个线程和程序的每次执行都得到相同的随机数?
最佳答案
关于Java 7 : ThreadLocalRandom generating the same random numbers,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7139525/