首页 > 解决方案 > 如何防止我的线程获得相同的随机数?

问题描述

我正在尝试让 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);
    }
}

标签: c#multithreading

解决方案


移出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

推荐阅读