scala.util.Random 线程安全吗? [英] Is scala.util.Random thread safe?

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

问题描述

我可以在多个线程中使用相同的 scala.util.Random 对象吗?

May I use the same scala.util.Random object in multiple threads?

推荐答案

PRNG 的重要特性之一是在给定相同种子时的可重复性.想象一下,您的代码在启动时遇到异常或崩溃.您希望重复该行为,以便调试问题.如果您让自己控制种子,则可以在调试问题时使用相同的种子一遍又一遍地启动程序.如果您从单个线程访问生成器,它将看到给定种子的相同序列.如果您从多个线程访问它,您将无法控制每个线程访问生成器的顺序,因此它们将看到序列的不同子集.因此,即使您可以依赖它,您也可能不想利用 Random 的线程安全性.

One of the important features of a PRNG is repeatability when given the same seed. Imagine your code hits an exception or crashes when you launch it. You want to repeat that behavior so you can debug the issue. If you give yourself control of the seed you can launch the program with the same seed over and over while you debug the problem. If you access the generator from a single thread it will see the same sequence for a given seed. If you access it from many threads you will not be able to control the order that each thread gets access to the generator and thus they will see different subsets of the sequence. So you may not want to take advantage of the thread safety of Random even if you can rely on it.

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

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