jdk7 中取得随机数,ThreadLocalRandom.current().nextDouble(); 来代替 Math.random();
好处是:
我们不再有从多个线程访问同一个随机数生成器实例的争夺。
取代以前每个随机变量实例化一个随机数生成器实例,我们可以每个线程实例化一个。
速度也更快。
测试代码:
public static void main(String[] args) {
final int MAX = 100000;
ThreadLocalRandom threadLocalRandom = ThreadLocalRandom.current();
long start = System.nanoTime(); //纳秒, 时间单位。一秒的10亿分之一
for (int i = 0; i < MAX; i++) {
threadLocalRandom.nextDouble();
}
long end = System.nanoTime() - start;
System.out.println("use time1 : " + end);
long start2 = System.nanoTime();
for (int i = 0; i < MAX; i++) {
Math.random();
}
long end2 = System.nanoTime() - start2;
System.out.println("use time2 : " + end2);
}
结果:
use time1 : 4344414
use time2 : 5515632
可以看出使用,ThreadLocalRandom.current().nextDouble()比Math.random()要快,并且更安全