Java 随机数 Random VS SecureRandom


1. Math.random() 静态方法

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

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() 时产生一个生成器 generator1,使用当前时间作为种子。
  • 线程2在第一次调用 random() 时产生一个生成器 generator2,使用当前时间作为种子。
  • 碰巧 generator1generator2 使用相同的种子,导致 generator1 以后产生的随机数每次都和 generator2 以后产生的随机数相同。

什么情况下随机数的生成线程安全: Math.random() 静态方法使用

  • 线程1在第一次调用 random() 时产生一个生成器 generator1,使用当前时间作为种子。
  • 线程2在第一次调用 random() 时发现已经有一个生成器 generator1,则直接使用生成器 generator1
Random random = new Random();

for (int i = 0; i < 5; i++) {
    System.out.println(random.nextInt());
}

结果:

-24520987
-96094681
-952622427
300260419
1489256498

Random类默认使用当前系统时钟作为种子:

Random random1 = new Random(10000);
Random random2 = new Random(10000);

for (int i = 0; i < 5; i++) {
    System.out.println(random1.nextInt() + " = " + random2.nextInt());
}

结果:

-498702880 = -498702880
-858606152 = -858606152
1942818232 = 1942818232
-1044940345 = -1044940345
1588429001 = 1588429001

3. java.util.concurrent.ThreadLocalRandom 工具类

ThreadLocalRandom 是 JDK 7 之后提供,也是继承至 java.util.Random。

public class JavaRandom {
    public static void main(String args[]) {
        new MyThread().start();
        new MyThread().start();
    }
}
class MyThread extends Thread {
    public void run() {
        for (int i = 0; i < 2; i++) {
            System.out.println(Thread.currentThread().getName() + ": " + ThreadLocalRandom.current().nextDouble());
        }
    }
}

结果:

Thread-0: 0.13267085355389086
Thread-1: 0.1138484950410098
Thread-0: 0.17187774671469858
Thread-1: 0.9305225910262372

4. java.Security.SecureRandom

也是继承至 java.util.Random。

Instances of java.util.Random are not cryptographically secure. Consider instead using SecureRandom to get a cryptographically secure pseudo-random number generator for use by security-sensitive applications.
SecureRandom takes Random Data from your os (they can be interval between keystrokes etc - most os collect these data store them in files - /dev/random and /dev/urandom in case of linux/solaris) and uses that as the seed.
操作系统收集了一些随机事件,比如鼠标点击,键盘点击等等,SecureRandom 使用这些随机事件作为种子。

SecureRandom 提供加密的强随机数生成器 (RNG),要求种子必须是不可预知的,产生非确定性输出。
SecureRandom 也提供了与实现无关的算法,因此,调用方(应用程序代码)会请求特定的 RNG 算法并将它传回到该算法的 SecureRandom 对象中。

  • 如果仅指定算法名称,如下所示:
    SecureRandom random = SecureRandom.getInstance("SHA1PRNG");

  • 如果既指定了算法名称又指定了包提供程序,如下所示:
    SecureRandom random = SecureRandom.getInstance("SHA1PRNG", "SUN");

使用:

>
    >commons-lang>
    >commons-lang>
    >2.6>
>

API 参考:https://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/RandomStringUtils.html

示例:

public class RandomStringDemo {
    public static void main(String[] args) {
        // Creates a 64 chars length random string of number.
        String result = RandomStringUtils.random(64, false, true);
        System.out.println("random = " + result);

        // Creates a 64 chars length of random alphabetic string.
        result = RandomStringUtils.randomAlphabetic(64);
        System.out.println("random = " + result);

        // Creates a 32 chars length of random ascii string.
        result = RandomStringUtils.randomAscii(32);
        System.out.println("random = " + result);

        // Creates a 32 chars length of string from the defined array of
        // characters including numeric and alphabetic characters.
        result = RandomStringUtils.random(32, 0, 20, true, true, "qw32rfHIJk9iQ8Ud7h0X".toCharArray());
        System.out.println("random = " + result);

    }
}

RandomStringUtils 类的实现上也是依赖了 java.util.Random 工具类:

  RandomStringUtils 类的定义

引用:
http://yangzb.iteye.com/blog/325264
Difference between java.util.Random and java.security.SecureRandom