Concurrent Random Numbers
In JDK 7, java.util.concurrent
includes a convenience class, ThreadLocalRandom
, for applications that expect to use random numbers from multiple threads or ForkJoinTask
s.
For concurrent access, using ThreadLocalRandom
instead of Math.random()
results in less contention and, ultimately, better performance.
All you need to do is call ThreadLocalRandom.current()
, then call one of its methods to retrieve a random number. Here is one example:
int r = ThreadLocalRandom.current() .nextInt(4, 77);
译文:
在JDK 7中,java.util.concurrent包括了一个便利的类,ThreadLocalRandom,对于应用程序希望用随机数在多线程中或者ForkJoinTasks.
对于并发使用,利用ThreadLocalRandom代替Math.Random()导致一些争议,基本上,性能上更好。
所有你要做的是调用ThreadLocalRandom.current(),然后调用它的方法重新获得一个随机数。这是一个实例:
int r = ThreadLocalRandom.current() .nextInt(4, 77);
For Further Reading
- Concurrent Programming in Java: Design Principles and Pattern (2nd Edition) by Doug Lea. A comprehensive work by a leading expert, who's also the architect of the Java platform's concurrency framework.
- Java Concurrency in Practice by Brian Goetz, Tim Peierls, Joshua Bloch, Joseph Bowbeer, David Holmes, and Doug Lea. A practical guide designed to be accessible to the novice.
- Effective Java Programming Language Guide (2nd Edition) by Joshua Bloch. Though this is a general programming guide, its chapter on threads contains essential "best practices" for concurrent programming.
- Concurrency: State Models & Java Programs (2nd Edition), by Jeff Magee and Jeff Kramer. An introduction to concurrent programming through a combination of modeling and practical examples.
- Java Concurrent Animated: Animations that show usage of concurrency features.