java> new Random与Math.random()创建随机数的区别与联系

要创建一个随机数,该怎么办?
java中提供了2种方式:Random类和Math.random()

它们有什么区别和联系呢?
Ramdom类

  1. 特点
    Random类对象是一个伪随机数生成器,使用48bit种子,随机数由线性同余生成器(linear congruential formula)生成。如果2个生成器的种子相同,那么它们会生成完全一样的随机数序列。而默认的种子是系统时间相关的一个数,具体来说是下面seedUniquifier() ^ System.nanoTime(),seedUniquifier()结果是8682522807148012L * 181783497276652981L = 8006678197202707420L。System.nanoTime()是jvm返回的纳秒级的高精度时间。
    /**
     * Creates a new random number generator. This constructor sets
     * the seed of the random number generator to a value very likely
     * to be distinct from any other invocation of this constructor.
     */
    public Random() {
        this(seedUniquifier() ^ System.nanoTime());
    }

    private static long seedUniquifier() {
        // L'Ecuyer, "Tables of Linear Congruential Generators of
        // Different Sizes and Good Lattice Structure", 1999
        for (;;) {
            long current = seedUniquifier.get();
            long next = current * 181783497276652981L;
            if (seedUniquifier.compareAndSet(current, next))
                return next;
        }
    }

    private static final AtomicLong seedUniquifier
        = new AtomicLong(8682522807148012L);
  1. 使用方式
    要生成随机数,必须得到Random实例,通过nextBoolean(), nextInt(), nextFloat()等来生成对应基本类型的随机数。通过nextXX()传入参数指定范围。

  2. 生成的随机数特点
    Random实例生成的随机数比较灵活,可以支持多种类型;

  3. 示例
    生成10个[0,100)的随机数

// java.util.Random
Random r = new Random();
for(int i = 0; i < 10; i++)
      int n = r.nextInt(100); // 生成0~100的随机数,不包括100

Math.random方法

  1. 特点
    Math.random本质上,也是一个Random实例,而且生成的是double类型随机数。不过是创建一个final类型的、种子使用默认种子的Random实例。
    public static double random() {
        return RandomNumberGeneratorHolder.randomNumberGenerator.nextDouble();
    }

    private static final class RandomNumberGeneratorHolder {
        static final Random randomNumberGenerator = new Random();
    }
  1. 使用方式
    直接调用Math.random() ,再对所需区间做四则运算

  2. 随机数特点
    范围[0, 1)

  3. 示例
    生成10个[5,20)的随机数

for (int i = 0; i < 10; i++) {
      int a = (int)(Math.random()*(20-10)) + 5;
}
原文地址:https://www.cnblogs.com/fortunely/p/14187065.html