2019/04/10 10:10

## 随机数

### 随机数发生器

//发生器1
X（n+1）= a * X(n) + b

//发生器2
X（n+1）= a * X(n)



### 随机数种子

//发生器1
X（n+1）= a * X(n) + b



Random random1 = new Random(100);
for (int i = 0; i < 10 ; i++) {
System.out.println(random1.nextInt(5));
}

System.out.println("-------------");

Random random2 = new Random(100);
for (int i = 0; i < 10 ; i++) {
System.out.println(random2.nextInt(5));
}


0
0
4
3
1
1
1
3
3
3
-------------
0
0
4
3
1
1
1
3
3
3
--------------


## Random类的局限性

Random类是JDK提供的一个随机数发生器。 我们看下Random类中nextInt方法的源代码：


public int nextInt(int bound) {
if (bound <= 0)
//关键代码点，这边会根据老的随机数种子生成新的随机数种子，然后会根据新生成的随机数种子生成随机数
int r = next(31);
int m = bound - 1;
if ((bound & m) == 0)  // i.e., bound is a power of 2
r = (int)((bound * (long)r) >> 31);
else {
for (int u = r;
u - (r = u % bound) + m < 0;
u = next(31))
;
}
return r;
}




protected int next(int bits) {
long oldseed, nextseed;
AtomicLong seed = this.seed;
do {
oldseed = seed.get();
//根据旧值计算新的种子
} while (!seed.compareAndSet(oldseed, nextseed));
return (int)(nextseed >>> (48 - bits));
}



ThreadLocalRandom random = ThreadLocalRandom.current();
random.nextInt();


• 《Java并发编程之美》

0
0 收藏

0 评论
0 收藏
0