随机类线程安全吗? [英] Is Random class thread safe?

查看:163
本文介绍了随机类线程安全吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在多个线程之间共享 Random 类的一个实例是否有效?并且特别是从多个线程调用 nextInt(int)

Is it valid to share one instance of the Random class between multiple threads? And to call nextInt(int) from multiple threads in particular?

推荐答案

它是线程安全的,因为它在多线程使用时仍然会生成随机数。

It is thread safe in the sense it will still generate random numbers when used by multiple threads.

Sun / Oracle JVM实现使用synchronized和AtomicLong作为种子来提高一致性跨线程。但它似乎并未在文档中的所有平台上得到保证。

The Sun/Oracle JVM implementation uses synchronized and AtomicLong as seed to improve consistency across threads. But it doesn't appear to be guarenteed across all platforms in the documentation.

我不会编写您的程序来要求这样的保证,特别是因为您无法确定将调用 nextInt()的订单。

I wouldn't write your program to require such a guarantee, especially as you cannot determine the order in which nextInt() will be called.

这篇关于随机类线程安全吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆