Random 与 ThreadLocalRandom 《 面试又翻车了》这次竟然和 Random 有关?
一、Random
Constructor and Description |
Random() Creates a new random number generator. |
Random(long seed) Creates a new random number generator using a single long seed. |
Method Summary
Modifier and Type | Method and Description |
protected int | next(int bits) Generates the next pseudorandom number. |
boolean | Returns the next pseudorandom, uniformly distributed boolean value from this random number generator's sequence. |
void | nextBytes(byte[] bytes) Generates random bytes and places them into a user-supplied byte array. |
double | Returns the next pseudorandom, uniformly distributed double value between 0.0 and 1.0 from this random number generator's sequence. |
float | Returns the next pseudorandom, uniformly distributed float value between 0.0 and 1.0 from this random number generator's sequence. |
double | Returns the next pseudorandom, Gaussian ("normally") distributed double value with mean 0.0 and standard deviation 1.0 from this random number generator's sequence. |
int | nextInt() Returns the next pseudorandom, uniformly distributed int value from this random number generator's sequence. |
int | nextInt(int n) Returns a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive), drawn from this random number generator's sequence. |
long | nextLong() Returns the next pseudorandom, uniformly distributed long value from this random number generator's sequence. |
void | setSeed(long seed) Sets the seed of this random number generator using a single long seed. |
Random 如果是多线程操作,则同一时刻只会有一个线程 CAS (Conmpare And Swap,比较并交换) 成功,其他失败的线程会通过自旋等待获取新种子,因此会有一定的性能消耗。
二、ThreadLocalRandom
ThreadLocalRandom 并不是像 Thread 那样使用 CAS 和自旋来获取新种子,而是在每个线程中使用每个线程中保存自己的老种子来生成新种子,因此就可以避免多线程竞争和自旋等待的时间,所以在多线程环境下性能更高。
在使用 ThreadLocalRandom 时需要注意一下,在多线程不能共享一个 ThreadLocalRandom 对象,否则会造成生成的随机数都相同
ThreadLocalRandom 在并发情况下的吞吐量约是 Random 的 5 倍。