一、Math.random
1Math.random内部使用java.util.Random实现
2 直接调用Math.random是产生一个[0,1)之间的随机数
public static void testMathRandom() {
System.out.println(Math.random());
System.out.println(Math.random());
}
输出:
0.9758482010371091
0.3419060236681194
二、java.util.Random
1 内部使用线性同余随机数发生器
2 nextInt(int n)取值范围[0,n)
3 nextInt()取值范围2的32次方个所有整数(正数、负数、零)
public static void testUtilRandom() {
long seed = System.nanoTime();
Random rand1 = new Random(seed);
Random rand2 = new Random(seed);
System.out.println(rand1.nextInt(100));
System.out.println(rand2.nextInt(100));
byte[] bytes = new byte[8];
rand1.nextBytes(bytes);
System.out.println(Arrays.toString(bytes));
rand2.nextBytes(bytes);
System.out.println(Arrays.toString(bytes));
}
输出:
70
70
[-25, -12, 30, -111, 123, 6, 11, 121]
[-25, -12, 30, -111, 123, 6, 11, 121]