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

编程入门 行业动态 更新时间:2024-10-26 23:32:48
本文介绍了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生成相同的随机数

本文发布于:2023-11-08 08:06:41,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1568819.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:随机数   Java   ThreadLocalRandom

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!