生成指定大小范围的随机数
生成随机数方式1:
Math.random()
公式: int sends = (int) (MIN + Math.random() * (MAX - MIN + 1));
生成随机数方式2 :
Random().nextInt(int bound)
公式: int randNumber =rand.nextInt(MAX - MIN + 1) + MIN
/**
* 生成[50000-60000]的随机数
*/
public static void printRandow() {
//生成随机数方式: Math.random()
long l = System.nanoTime();
int sends = (int) (50000 + Math.random() * (10000 + 1));
System.out.println(sends+" TT :"+(System.nanoTime()-l));
//生成随机数方式 :Random().nextInt(int bound)
long sl = System.nanoTime();
Random rand = new Random();
int randNumber = rand.nextInt(10001) + 50000;
System.out.println(randNumber+" TT :"+(System.nanoTime()-sl));
}
打印结果:
50190 1T :179146
56962 2T :85218
两种方式的比对:
两种方法都可以生成指定大小范围随机数,区别在于:
1.Math.random()生成随机数不需要new对象对内存占用较小,但是相对耗时;
2.new Random().nextInt(int bound) 生成随机数new出对象 Random()然后生成随机数,相对吃内存,但是时间确只有Math.random()的一半左右;
有点类似是方式1是:时间换空间,方式 2是:空间换时间;
随机数中的一个问题
代码说话:
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
System.out.println(creatRandom(1000));
}
}
/**
*生成随机数
*/
public static long creatRandom(int seeds) {
return new Random(1000).nextInt();
}
结果:
-1244746321
-1244746321
-1244746321
-1244746321
-1244746321
-1244746321
-1244746321
-1244746321
-1244746321
-1244746321
正确的代码:
private static Random random;
public static long creatRandom() {
if (random == null) {
random = new Random(2000);
}
return random.nextInt();
}
问题的根本原因是:JavaJDK中的随机数是一个伪随机数:
【Random类的实例用于生成伪随机数流。此类使用 48 位的种子,使用线性同余公式对其进行修改(请参阅 Donald Knuth 的《The Art of Computer Programming, Volume 2》,第 3.2.1 节)】
在原码中是一个固定的算法线性算法,所以每次都new出Random 对象ji即每次都是一个初始化的AtomicLong 的 seed,再同过一个固定的算法(protected int next(int bits))所以结果都是一个结果。