Bootstrap

Java 生成随机数的 5 种方式,你知道几种?

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() + ": " + Math.random());

}

}

}

结果:

Thread-1: 0.8043581595645333 Thread-0: 0.9338269554390357 Thread-1: 0.5571569413128877 Thread-0: 0.37484586843392464

2.java.util.Random 工具类

基本算法:linear congruential pseudorandom number generator (LGC) 线性同余法伪随机数生成器缺点:可预测

An attacker will simply compute the seed from the output values observed. This takes significantly less time than 2^48 in the case of java.util.Random. 从输出中可以很容易计算出种子值。It is shown that you can predict future Random outputs observing only two(!) output values in time roughly 2^16. 因此可以预测出下一个输出的随机数。You should never use an LCG for security-critical purposes.在注重信息安全的应用中,不要使用 LCG 算法生成随机数,请使用 SecureRandom。

使用:

Random random = new Random();

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

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

}

结果:

-24520987 -96094681 -952622427 300260419 1489256498

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

public Ra

;