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

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

问题描述

在多个线程之间共享 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 实现使用同步和 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.

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

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