JAVA中Random类的Random r=new Random()和Random r=new Random(seedValue)的区别

区别在于:

 Random r=new Random()每次运行程序时seedValue不一样,得到的随机数序列不一样,一般会这么用

Random r=new Random(seedValue): 每次运行程序得到的随机数序列都是一样的。例如第一次运行程序得到的随机数是 2, 4, 1, 5, 7。那么重启程序,再次得到的随机数还是2, 4, 1, 5, 7

原因:

Random产生的随机数实际上属于伪随机数,是按照一定算法计算出来的。构造方法如果没有传入随机种子的话,系统会默认采用系统时间作为随机种子。

[java]  view plain  copy
  1. /** 
  2.  * Creates a new random number generator. This constructor sets 
  3.  * the seed of the random number generator to a value very likely 
  4.  * to be distinct from any other invocation of this constructor. 
  5.  */  
  6. public Random() { this(++seedUniquifier + System.nanoTime()); }  
  7. private static volatile long seedUniquifier = 8682522807148012L;  
  8.   
  9. /** 
  10.  * Creates a new random number generator using a single {@code long} seed. 
  11.  * The seed is the initial value of the internal state of the pseudorandom 
  12.  * number generator which is maintained by method {@link #next}. 
  13.  * 
  14.  * <p>The invocation {@code new Random(seed)} is equivalent to: 
  15.  *  <pre> {@code 
  16.  * Random rnd = new Random(); 
  17.  * rnd.setSeed(seed);}</pre> 
  18.  * 
  19.  * @param seed the initial seed 
  20.  * @see   #setSeed(long) 
  21.  */  
  22. public Random(long seed) {  
  23.     this.seed = new AtomicLong(0L);  
  24.     setSeed(seed);  
  25. }  

猜你喜欢

转载自blog.csdn.net/Luna_ll/article/details/79931431
今日推荐