Is Random class thread safe?

2019-01-22 04:46发布

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

8条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-01-22 05:50

It is thread safe, although it wasn't always.

See http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6362070 for more details.

查看更多
霸刀☆藐视天下
3楼-- · 2019-01-22 05:52

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

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.

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

查看更多
登录 后发表回答