IT行业云计算java培训课程学习笔记|ThreadLocalRandom的使用方法
从Java语言出现至今一直在软件开发中占据重要位置,Java编程语言拥有庞大的知识体系,想要掌握这些内容的话,就需要我们在学习Java技术时打好基础很重要的,因此今天北京八维教育培训学校分享整理好的一份IT行业云计算java培训课程学习笔记中的ThreadLocalRandom的使用方法。

Java中ThreadLocalRandom的使用 在Java中我们通常会需要使用到Java.util.Random来便利的生产随机数。但是Random是线程安全的,如果要在线程环境中的话就有可能产生性能瓶颈。我们以Random中常用的nextInt方法为例来具体看一下:public int nextInt() { return next(32); } 复制代码nextInt方法实际上调用了下面的方法:protected int ext(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)); } 复制代码从代码中我们可以看到,方法内部使用了AtomicLong,并调用了它的compareAndSet方法来保证线程安全性。所以这个是一个线程安全的方法。其实在多个线程环境中,Random根本就需要共享实例,那么该怎么处理呢?在JDK 7 中引入了一个ThreadLocalRandom的类。ThreadLocal大家都知道就是线程的本地变量,而ThreadLocalRandom就是线程本地的Random。我们看下怎么调用:

public void testRandom() throws InterruptedException { ExecutorService executorService=Executors.newFixedThreadPool(2); Random random = new Random(); List<Callable
} 复制代码public class ThreadLocalRandomUsage {
@Benchmark@BenchmarkMode(Mode.AverageTime)@OutputTimeUnit(TimeUnit.MICROSECONDS)public void testThreadLocalRandom() throws InterruptedException { ExecutorService executorService=Executors.newFixedThreadPool(2); List<Callable
} 复制代码分析运行结果,我们可以看出ThreadLocalRandom在多线程环境中会比Random要快。


