c# - 如何防止我的线程获得相同的随机数?
问题描述
我正在尝试让 3 个线程生成随机数,但它们一直在获取相同的数字。我对线程做错了什么?
这基本上是我的“驱动程序”:
public int[] GetOffers()
{
_3InsuranceCompanies guys = new _3InsuranceCompanies();
Thread thread1 = new Thread(new ThreadStart(guys.sellers));
Thread thread2 = new Thread(new ThreadStart(guys.sellers));
Thread thread3 = new Thread(new ThreadStart(guys.sellers));
thread1.Start();
thread2.Start();
thread3.Start();
int[] offers = new int[3];
offers[0] = guys.insurance_sellers[0];
offers[1] = guys.insurance_sellers[1];
offers[2] = guys.insurance_sellers[2];
return offers;
}
这是线程用作启动方法的类:
public class _3InsuranceCompanies
{
public int[] insurance_sellers = new int[3];
public _3InsuranceCompanies()
{
for(int x = 0; x < 3; x++)
{
insurance_sellers[x] = new Random().Next(60, 200);
}
}
public void sellers()
{
Random rnd = new Random();
int price;
// simulated negotiation. some threads might be good at negotiating so price will reduce
// other threads might be bad at negotiating so price can possible go higher than before
Monitor.TryEnter(insurance_sellers);
for (int x = 0; x < 3; x++)
{
price = rnd.Next(70, 200);
if (Math.Abs(insurance_sellers[0] - price) < 30)
insurance_sellers[0] = price;
if (Math.Abs(insurance_sellers[1] - price) < 30)
insurance_sellers[1] = price;
if (Math.Abs(insurance_sellers[2] - price) < 30)
insurance_sellers[2] = price;
}
Monitor.Exit(insurance_sellers);
}
}
解决方案
移出new Random
方法并使其成为静态。
static Random rnd = new Random();
public _3InsuranceCompanies()
{
for(int x = 0; x < 3; x++)
{
insurance_sellers[x] = rnd.Next(60, 200);
}
}
发生了什么?
以下段落来自从的文档中实例化随机数生成器Random
如果相同的种子用于不同的 Random 对象,它们将生成相同的随机数序列。这对于创建处理随机值的测试套件或重玩从随机数派生数据的游戏很有用。
这是一个小例子:
var count = 10;
var randoms = new int[count];
for (int x = 0; x < count; x++) { randoms[x] = new Random().Next(60, 200); }
Console.WriteLine($"With many new Random()s: {string.Join(",", randoms)}");
var rnd = new Random();
var randoms2 = new int[count];
for (int x = 0; x < count; x++) { randoms2[x] = rnd.Next(60, 200); }
Console.WriteLine($"With one Random: {string.Join(",", randoms2)}");
输出
With many new Random()s: 70,70,70,70,70,70,70,70,70,70
With one Random: 70,89,114,197,89,117,176,64,61,103
推荐阅读
- sql - 你如何在 Rails w/PostgreSQL 中查询 3 种不同的模型?
- c - 当服务器发送关闭信号时使用 libcurl 关闭 websocket 连接
- python-3.x - Flask-Login 使用 Radius
- java - 使用@MapsId 在双向@OneToOne 上级联
- jquery - 使用 jQuery 更改 css 动画持续时间
- java - message.setFlag(Flags.Flag.SEEN, true); 工作正常并将邮件标记为已读,但如果我在 Gmail 中打开邮件,Same 不会更新
- reactjs - 'string[]' 类型的参数不能分配给'string' 类型的参数
- python - 查找数组中重复元素的长度和起始索引的快速方法
- javascript - 在 React onClick() 中没有调用函数
- vb.net - 如何让 Outlook 识别整个链接,而不仅仅是其中的一部分?