multithreading - New thread for each object in C# -
this question has answer here:
i have following code:
thread[] threadarray= new thread[3]; myobject[] objectarray = new myobject[3]; (int = 0; < 3; i++) { //create new hotelsupplier object objectarray[i] = new myobject(); //create array of threads , start new thread each hotelsupplier threadarray[i] = new thread(new threadstart(objectarray[i].run)); //store name of thread threadarray[i].name = i.tostring(); //start thread threadarray[i].start(); }
i creating 3 objects , 3 threads. of objects stored in array, of threads stored in array.
the run method in myobject generates random number between min , max
random random = new random(); double min = 50.00; double max = 500.00; double price = random.nextdouble() * (max - min) + min; console.writeline("generating price: " + price);
my output:
generating price: 101.271334780041 generating price: 101.271334780041 generating price: 101.271334780041
i expect 3 different random numbers instead of 1 since each thread thought running on different object.
what doing wrong , not understand threads?
your original code causing random
instances seeded same value.
the lowest impact way fix move code create random
:
void run() { //... random random = new random(); //... }
outside of run
method , private static
variable, becomes:
private static random random = new random(); void run() { //... }
so seeded once across instances of myobject
.
Comments
Post a Comment