I'm trying to make 3 threads generate random numbers, but they keep picking up the same number. What am I doing wrong with the threads?
Here is my "Driver" essentially:
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;
}
Here is the class the threads are using as a start method:
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);
}
}