问题描述
正在浏览Java 7的新功能并发现添加了这个新类:
Was going through Java 7 new features and found this new class added:
正在研究如何实施导致较少的争用和更好的性能。
Was researcing how this is implemented resulting in less Contention and better performance.
推荐答案
实际上,两者之间的区别在于同步。 Math#random()
可能同时由多个线程调用,因此必须同步,而 ThreadLocalRandom
是一个不同步的版本随机
是线程绑定意味着每个线程都有自己的(更快)分配。
Effectively, the difference between the two is synchronization. Math#random()
may be called by multiple threads simultaneously thus having to synchronize, while ThreadLocalRandom
is an unsynchronized version of Random
that is thread bound meaning each thread gets its own (faster) allocation.
如果你仔细看看在实现中,你会发现 Math#random()
使用单个 java.util.Random
的实例生成随机数,其中 ThreadLocalRandom
为每个线程分配一个实例,从而消除了这种意义上的争用。
If you take a closer look at the implementation, you will find out that Math#random()
uses a single instance of java.util.Random
to generate random numbers, where ThreadLocalRandom
allocates an instance per thread thus eliminating contention in that sense.
ThreadLocalRandom
实现并发其中 Math#random()
实现同步。
这篇关于ThreadLocalRandom如何减少争用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!