ThreadLocalRandom 上的 Random [英] Random over ThreadLocalRandom
问题描述
java.util.Random 的实例是线程安全的.然而,并发跨线程使用同一个 java.util.Random 实例可能会遇到争用和随之而来的性能不佳.考虑改为使用多线程设计中的 ThreadLocalRandom.
Instances of java.util.Random are threadsafe. However, the concurrent use of the same java.util.Random instance across threads may encounter contention and consequent poor performance. Consider instead using ThreadLocalRandom in multithreaded designs.
什么样的竞争导致性能不佳?任何人都可以请在这里解释一下吗?我不知道 Random 和 ThreadLocalRandom 中的什么算法使它们不同.
What kind of contention and thus poor performance ? Can anybody please, explain me here ? I don't know what algorithm goes inside Random and ThreadLocalRandom that makes them different.
推荐答案
这可能会有所帮助:
http://thoughtfuljava.blogspot.com/2012/09/prefer-threadlocalrandom-over-random.html
引自:
通常要生成随机数,我们要么创建 java.util.Random
的实例,要么创建 Math.random()
的实例 - 它在内部创建一个 java.util.Random
在第一次调用时.但是,在并发应用程序中使用上述方法会导致争用问题.
Normally to generate random numbers, we either do create an instance of java.util.Random
or Math.random()
- which internally creates an instance of java.util.Random
on first invocation. However, in a concurrent applications usage of above leads to contention issues.
Random
是线程安全的,可供多线程使用.但是如果多个线程使用同一个 Random
实例,同一个种子就会被多个线程共享.它会导致多个线程之间的争用,从而导致性能下降.
Random
is thread safe for use by multiple threads. But if multiple threads use the same instance of Random
, the same seed is shared by multiple threads. It leads to contention between multiple threads and so to performance degradation.
ThreadLocalRandom
是上述问题的解决方案.ThreadLocalRandom
每个线程都有一个 Random
实例并防止争用.
ThreadLocalRandom
is solution to above problem. ThreadLocalRandom
has a Random
instance per thread and safeguards against contention.
因此,基本上,每个线程使用一个随机实例可以让您停止同步所有线程必须使用的种子.
So, basically, using a random instance per thread allows you to stop synchronizing on the seed which must be used by all threads.
这篇关于ThreadLocalRandom 上的 Random的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!