每个线程的ThreadLocalRandom或new Random

时间:2021-06-11 07:09:01

Is there any difference when I create in each thread new java.util.Random object or use the ThreadLocalRandom.current().nextInt(3); ? From what I've read, ThreadLocalRandom should be used instead of using the same instance of java.util.Random for all threads but what if a create a new instance for each thread?

当我在每个线程中创建新的java.util.Random对象或使用ThreadLocalRandom.current()时,有什么不同吗。nextInt(3); ?从我所读到的,应该使用ThreadLocalRandom而不是为所有线程使用相同的java.util.Random实例,但是如果为每个线程创建一个新实例呢?

When should i use java.util.Random and when ThreadLocalRandom if i need to generate random numbers in multiple threads?

什么时候我应该使用java.util.Random和ThreadLocalRandom,如果我需要在多个线程中生成随机数?

每个线程的ThreadLocalRandom或new Random

1 个解决方案

#1


2  

If you create your own threads, like you do here, it makes no difference.

如果您创建自己的线程,就像在这里一样,它没有任何区别。

But if your code is called from different threads beyond your control, ThreadLocalRandom is the correct one to use.

但是,如果您的代码是从超出您控制范围的不同线程调用的,则ThreadLocalRandom是正确使用的。

There is one difference that does matter though: for obvious reasons you can't set a seed for ThreadLocalRandom. So if you want to have repeatable sequences, you need to create your own Random instances. (But then if you're running multiple threads, having your RNGs seeded to the same value doesn't always guarantee repeatable behaviour anyway.)

但是有一个区别很重要:出于显而易见的原因,您无法为ThreadLocalRandom设置种子。因此,如果您想拥有可重复的序列,则需要创建自己的Random实例。 (但是如果你正在运行多个线程,那么将你的RNG接种到相同的值并不总能保证可重复的行为。)

I would personally use ThreadLocalRandom in all cases where I don't need repeatable sequences.

在我不需要可重复序列的所有情况下,我个人会使用ThreadLocalRandom。

#1


2  

If you create your own threads, like you do here, it makes no difference.

如果您创建自己的线程,就像在这里一样,它没有任何区别。

But if your code is called from different threads beyond your control, ThreadLocalRandom is the correct one to use.

但是,如果您的代码是从超出您控制范围的不同线程调用的,则ThreadLocalRandom是正确使用的。

There is one difference that does matter though: for obvious reasons you can't set a seed for ThreadLocalRandom. So if you want to have repeatable sequences, you need to create your own Random instances. (But then if you're running multiple threads, having your RNGs seeded to the same value doesn't always guarantee repeatable behaviour anyway.)

但是有一个区别很重要:出于显而易见的原因,您无法为ThreadLocalRandom设置种子。因此,如果您想拥有可重复的序列,则需要创建自己的Random实例。 (但是如果你正在运行多个线程,那么将你的RNG接种到相同的值并不总能保证可重复的行为。)

I would personally use ThreadLocalRandom in all cases where I don't need repeatable sequences.

在我不需要可重复序列的所有情况下,我个人会使用ThreadLocalRandom。