public static ThreadLocalRandom current(){
if (UNSAFE.getInt(Thread.currentThread(), PROBE)==0)
localInit();
return instance;}
static final void localInit(){int p = probeGenerator.addAndGet(PROBE_INCREMENT);int probe =(p ==0)? 1: p;// skip 0long seed = mix64(seeder.getAndAdd(SEEDER_INCREMENT));
Thread t = Thread.currentThread();
UNSAFE.putLong(t, SEED, seed);
UNSAFE.putInt(t, PROBE, probe);}
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
如果没有初始化,先进行初始化,这里我们的seed不再是全局变量了。我们的线程中有三个变量:
/** The current seed for a ThreadLocalRandom */
@sun.misc.Contended("tlr")long threadLocalRandomSeed;/** Probe hash value; nonzero if threadLocalRandomSeed initialized */
@sun.misc.Contended("tlr")int threadLocalRandomProbe;/** Secondary seed isolated from public ThreadLocalRandom sequence */
@sun.misc.Contended("tlr")int threadLocalRandomSecondarySeed;
@BenchmarkMode({Mode.AverageTime})
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@Warmup(iteratinotallow=3,time=5, timeUnit = TimeUnit.SECONDS)
@Measurement(iteratinotallow=3,time=5)
@Threads(4)
@Fork(1)
@State(Scope.Benchmark)
public class Myclass {
Random random = new Random();
ThreadLocalRandom threadLocalRandom = ThreadLocalRandom.current();
@Benchmark
public int measureRandom(){
return random.nextInt();}
@Benchmark
public int threadLocalmeasureRandom(){
return threadLocalRandom.nextInt();}}