ThreadLocalRandom类用法

JDK7的JUC包新引入了 ThreadLocalRandom 这个类,来应对多线程场景下随机数生成问题。

以前生成随机数一般用Random类,虽然该类是线程安全的,但是底层用的CAS,在多线程环境下效率会降低,故此JDK7以后推荐用 ThreadLocalRandom来生成随机数。(Random和ThreadLocalRandom生成的都是伪随机数,可被预测,要是对随机数安全性有要求,应考虑Random的另一个子类 SecureRandom)

简单看一下ThreadLocal的源码,发现它是单例的

    /** Constructor used only for static singleton */
    private ThreadLocalRandom() {
        initialized = true; // false during super() call
    }

    /** The common ThreadLocalRandom */
    static final ThreadLocalRandom instance = new ThreadLocalRandom();
再看类的文档描述
* <p>Usages of this class should typically be of the form:
* {@code ThreadLocalRandom.current().nextX(...)} (where
* {@code X} is {@code Int}, {@code Long}, etc).
* When all usages are of this form, it is never possible to
* accidently share a {@code ThreadLocalRandom} across multiple threads.

要获取它的单例对象,应使用current()方法,其他的操作就和Random一样,比如nextInt()、nextLong()、nextDouble()等等。

用法示例:

/**
 * ThreadLocalRandom测试
 */
public class ThreadLocalRandomTest {

    public static void main(String[] args) {
        for (int i = 0; i < 10; i++) {
            new Thread(() -> System.out.println(
                    Thread.currentThread().getName() + "生成的随机数: " +
                    ThreadLocalRandom.current().nextInt(10))).start();
        }
    }
}

 执行的结果大致如下:

最后经过查阅不同大佬的文章,发现ThreadLocalRandom使用的时候有个坑,要注意,在多线程时,要保证每个线程单独持有它的实例,而不是线程公有,比如将上面的代码调整一下,如下

错误示例

/**
 * ThreadLocalRandom测试--错误示例
 */
public class ThreadLocalRandomTest {

    public static void main(String[] args) {
        // 错误用法,会导致多线程产生相同的随机数
        ThreadLocalRandom random = ThreadLocalRandom.current();
        for (int i = 0; i < 10; i++) {
            new Thread(() -> System.out.println(
                    Thread.currentThread().getName() + "生成的随机数: " +
                    random.nextInt(10))).start();
        }
    }
}

 执行的结果大致如下:

发现竟然生成了相同的随机数!!!

产生该错误的原因,可以参考该回答

ThreadLocalRandom为什么多线程随机数相同? - 知乎谢邀~因为ThreadLocalRandom用法并不是这样的,请读一下current()方法的源码注释 /** * Returns …https://www.zhihu.com/question/376227700/answer/1052322532

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值