本文介绍了Java 7:ThreadLocalRandom生成相同的随机数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用Java 7的 ThreadLocalRandom 和看到它在多个线程中生成完全相同的随机数。
I'm trying out Java 7's ThreadLocalRandom and see that it is generating exactly the same random numbers across multiple threads.
这是我的代码,我创建了5个线程,每个线程打印出5个随机数:
Here is my code, in which I create 5 threads and each thread prints out 5 random numbers:
//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,为什么我为每个线程和每次执行程序获得相同的随机数?
Why am I getting the same random numbers for each thread and for every execution of the program?
推荐答案似乎有一个关于这个问题的漏洞。请参见此处和这里
Seems like there's an open bug regarding this issue. See here and here
更多推荐
Java 7:ThreadLocalRandom生成相同的随机数
发布评论