Is Random class thread safe?

前端 未结 8 928
臣服心动
臣服心动 2020-12-13 11:53

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条回答
  • 2020-12-13 12:19

    Acording to the documentation, Math.random() guarantees it's safe for use by multiple threads. But the Random class does not. I would assume then you'll have to synchronize that yourself.

    0 讨论(0)
  • 2020-12-13 12:28

    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.

    0 讨论(0)
提交回复
热议问题