Random.Next() sometimes returns same number in separate threads

前端 未结 3 1713
别那么骄傲
别那么骄傲 2020-12-06 17:44

I have the following class

class Program
{
   static Random _Random = new Random();

   static void Main(string[] args)
   {
      ...
      for (int i = 0;          


        
3条回答
  •  情歌与酒
    2020-12-06 18:17

    Your example code only shows one use of _Random per thread. Assuming this is the case, you could also generate the random number in the main for loop and pass the random number into each thread as a parameter.

     for (int i = 0; i < no_threads; ++i)
     {
          var thread = new Thread(new ThreadStart(Send));
          thread.Start(_Random.Next(999999));
     }
    

    and then modify your thread function to accept the parameter:

     static void Send(int device_id)
     {
        ...
        //int device_id = _Random.Next(999999);
        ...
     }   
    

提交回复
热议问题