jdk7 - Java ThreadLocalRandom产生重复随机数问题
本文介绍了jdk7 - Java ThreadLocalRandom产生重复随机数问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问 题
为什么多线程产生一样的随机数?是写法错误吗?
另外,如果换成 Random实例,为什么就不一样了,不是说前者仅是后者的优化吗?
public class Task implements Runnable {
private static Random random = ThreadLocalRandom.current();
// private static Random random = new Random();
@Override
public void run() {
System.out.println(random.nextInt());
}
public static void main(String[] args) {
ExecutorService taskPool = Executors.newCachedThreadPool();
for(int n = 1; n < 10; n++) {
taskPool.submit(new Task());
}
taskPool.shutdown();
}
}
-1667209487
-1667209487
-1667209487
-1667209487
-1667209487
-1667209487
-1667209487
-1667209487
-1667209487
-1999664185
1468557546
183343793
770001684
1625714058
-2134889142
1456310974
-191722744
1763443594
解决方案
System.out.println(threadLocalRandom.nextInt(4, 77));
System.out.println(threadLocalRandom.nextInt(4, 77));
System.out.println(threadLocalRandom.nextInt(4, 77));
每个线程都是15,30,14,这就是为啥是伪随机数
这篇关于jdk7 - Java ThreadLocalRandom产生重复随机数问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文