在ThreadLocalRandom上随机 [英] Random over ThreadLocalRandom

查看:82
本文介绍了在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实例,则多个线程共享相同的种子。它会导致多个线程之间的争用,从而导致性能下降。

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上随机的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆