Random 高并发下的缺点
- Random是线程安全的,但是并不是“高并发”的
- 大量CAS导致CPU飙高
Random random = new Random();
System.out.println(random.nextInt(100));
一、奇怪的命名
- random.nextInt() 奇怪的命名,获取值为什么不是通常的 “get”, “create”,“generate”等常见的命名.random生成的随机数,并不是真正的随机,它有一个种子的概念,是根据种子值来计算【下一个】值的,如果种子值相同,那么它生成出来的随机数也必定相等,也就是“确定的输入产生确定的输出”。
二、源码解析
public int nextInt(int bound) {
if (bound <= 0)
throw new IllegalArgumentException(BadBound);
// 1.根据老的种子生成新的种子
int r = next(31);
// 2.根据新的种子计算随机数
int m = bound - 1;
if ((bound & m) == 0) // i.e., bound is a power of 2
r = (int)((bound * (long)r)