Java 7:ThreadLocalRandom 生成相同的随机数
我正在尝试 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,
为什么每个线程和程序的每次执行都会获得相同的随机数?
I'm trying out Java 7's ThreadLocalRandom and see that it is generating exactly the same random numbers across multiple threads.
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();
}
Output:
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
似乎有一个关于此问题的未解决的错误。请参阅此处和此处
Seems like there's an open bug regarding this issue. See here and here
谷歌搜索“ThreadLocalRandom源”给了我 http://www.assembla.com/code/scala-eclipse-toolchain/git/nodes/src/forkjoin/scala/concurrent/forkjoin/ThreadLocalRandom.java
长/短:它使用
ThreadLocal
调用无参数构造函数来构造无参数构造函数是
Random 使用唯一的种子调用 this(long)
但构造函数即
不是文档中的预期行为
,并且 ThreadLocalRandom 不/不能使用私有
seed
googling for the "ThreadLocalRandom source" gave me http://www.assembla.com/code/scala-eclipse-toolchain/git/nodes/src/forkjoin/scala/concurrent/forkjoin/ThreadLocalRandom.java
long/short of it: it uses a
ThreadLocal<ThreadLocalRandom>
which calls the no-arg constructor for constructionthat no-arg constructor is
the no-arg super in Random calls this(long) with a unique seed
HOWEVER that constructor does
i.e. not the expected behavior from documentation
and ThreadLocalRandom doesn't/can't use the private
seed
这不是因为线程是在大致相同的时间创建的,因此从计时器中获得了相同的值吗?我的印象就是它是如何工作的,尽管我可能是错的。
Isn't this because the threads are being created at roughly the same time and thus getting seeded the same value from the timer? I was under the impression that was how that worked, though I may be mistaken.