java 产生n个5以内的随机数_Java 生成随机数的 5 种方式,你知道几种?

1. Math.random() 静态方法

产生的随机数是 0 - 1 之间的一个 double,即 0 <= random <= 1。

使用:

for (int i = 0; i < 10; i++) {

System.out.println(Math.random());

}

结果:

0.3598613895606426 0.2666778145365811 0.25090731064243355 0.011064998061666276 0.600686228175639 0.9084006027629496 0.12700524654847833 0.6084605849069343 0.7290804782514261 0.9923831908303121

实现原理:

When this method is first called, it creates a single new pseudorandom-number generator, exactly as if by the expression new java.util.Random() This new pseudorandom-number generator is used thereafter for all calls to this method and is used nowhere else.

当第一次调用 Math.random() 方法时,自动创建了一个伪随机数生成器,实际上用的是 new java.util.Random()。当接下来继续调用 Math.random() 方法时,就会使用这个新的伪随机数生成器。

源码如下:

public static double random() {

Random rnd = randomNumberGenerator;

if (rnd == null) rnd = initRNG(); // 第一次调用,创建一个伪随机数生成器

return rnd.nextDouble();

}

private static synchronized Random initRNG() {

Random rnd = randomNumberGenerator;

return (rnd == null) ? (randomNumberGenerator = new Random()) : rnd; // 实际上用的是new java.util.Random()

}

This method is properly synchronized to allow correct use by more than one thread. However, if many threads need to generate pseudorandom numbers at a great rate, it may reduce contention for each thread to have its own pseudorandom-number generator.

initRNG() 方法是 synchronized 的,因此在多线程情况下,只有一个线程会负责创建伪随机数生成器(使用当前时间作为种子),其他线程则利用该伪随机数生成器产生随机数。

因此 Math.random() 方法是线程安全的。

什么情况下随机数的生成线程不安全:

线程1在第一次调用 random() 时产生

你可能感兴趣的:(java,产生n个5以内的随机数)