Oracle Java documentation说:
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.
可能是糟糕表现的原因?
解决方法
在内部,java.util.Random保持AtomicLong与当前的种子,并且每当请求一个新的随机数时,争用更新种子.
从java.util.Random的实现:
protected int next(int bits) { long oldseed,nextseed; AtomicLong seed = this.seed; do { oldseed = seed.get(); nextseed = (oldseed * multiplier + addend) & mask; } while (!seed.compareAndSet(oldseed,nextseed)); return (int)(nextseed >>> (48 - bits)); }
另一方面,ThreadLocalRandom通过每个线程有一个种子来确保种子更新而不面对任何争用.