C# 如何防止线程获得相同的随机数?

C# 如何防止线程获得相同的随机数?,c#,multithreading,C#,Multithreading,我试着让3个线程生成随机数,但它们总是选择相同的数字。我的线怎么了 这是我的“驱动力”: public int[] GetOffers() { _3InsuranceCompanies guys = new _3InsuranceCompanies(); Thread thread1 = new Thread(new ThreadStart(guys.sellers)); Thread thread2 = new Thread(new T

我试着让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);
    }
}
公共类保险公司
{
公共整数[]保险\卖方=新整数[3];
公共保险公司()
{
对于(int x=0;x<3;x++)
{
保险卖方[x]=new Random().Next(60200);
}
}
公营房屋卖方()
{
随机rnd=新随机();
国际价格;
//模拟谈判。一些线程可能擅长谈判,所以价格会降低
//其他线程可能不擅长谈判,因此价格可能会比以前更高
监控中心(保险卖方);
对于(int x=0;x<3;x++)
{
价格=下一个(70200)rnd;
if(数学Abs(保险卖方[0]-价格)<30)
保险卖方[0]=价格;
if(数学Abs(保险卖方[1]-价格)<30)
保险卖方[1]=价格;
if(数学Abs(保险卖方[2]-价格)<30)
保险卖方[2]=价格;
}
监控、退出(保险卖家);
}
}

新随机数
移出该方法并使其成为静态

static Random rnd = new Random();

public _3InsuranceCompanies()
    {
        for(int x = 0; x < 3; x++)
        {
            insurance_sellers[x] = rnd.Next(60, 200);
        }
    }

输出

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