public class RandomTest{
 static Random random = new Random();
 
    static int r1(int n) {
        return (int)(Math.random() * n);
    }
    static int r2(int n) {
        return random.nextInt(n);
    }
 
 public static void main(String[] args) {
  long t1 = System.nanoTime();
  for (int i=0;i<10000;i++) {
   r1(1024);
  }
  long t2 = System.nanoTime();
  System.out.println(t2 - t1);
  t1 = System.nanoTime();
  for (int i=0;i<10000;i++) {
   r2(1024);
  }
  t2 = System.nanoTime();
  System.out.println(t2 - t1);
 }
}


  结果:

  3422502
  1335365

  结论:无论从准确性和效率,nextInt(n)都比Math.random()要好。

  三、安全性

  Random类的next(n)方法依靠确定的seed种子来计算nextseed的值(seed位48位的bit),尽管使用了各种运算,但结果仍然是线性可预测的。


    protected int next(int bits) {
        long oldseed, nextseed;
        AtomicLong seed = this.seed;
        do {
     oldseed = seed.get();
     nextseed = (oldseed * multiplier + addend) & mask;
        } while (!seed.compareAndSet(oldseed, nextseed));
        return (int)(nextseed >>> (48 - bits));
    }