Java的随机数

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 TypeMethod and Description
protected int

next(int bits)

Generates the next pseudorandom number.

boolean

nextBoolean()

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

nextDouble()

Returns the next pseudorandom, uniformly distributed double value between 0.0 and 1.0 from this random number generator's sequence.

float

nextFloat()

Returns the next pseudorandom, uniformly distributed float value between 0.0 and 1.0 from this random number generator's sequence.

double

nextGaussian()

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 倍。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值