2017-05-12 44 views
0

我想創建三個線程。每個線程都是一個球員,並有三個鏡頭。這些鏡頭是從線程中隨機生成的數字。我試圖通過這如何設置一個線程來隨機生成的數字

static int counter = 0; 

     static Thread player1 = new Thread(new ThreadStart(Player1Shot)); 
     static Thread player2 = new Thread(new ThreadStart(Player2Shot)); 
     static Thread player3 = new Thread(new ThreadStart(Player3Shot)); 

     static readonly ThreadLocal<Random> random = 
      new ThreadLocal<Random>(() => new Random(Interlocked.Increment(ref counter))); 

static void Main(string[] args) 
     { 
      player1.Name = "David"; 
      player2.Name = "James"; 
      player3.Name = "Mike"; 

      player1.Start(); 
      player2.Start(); 
      player3.Start(); 
      //Console.WriteLine("{0}", random.Value.Next()); 
      Console.ReadLine(); 
     } 

     public static void Player1Shot() 
     { 
      try 
      { 
       for (int i = 0; i < 3; i++) 
       { 
        Console.WriteLine("{0} shot {1}\n", Thread.CurrentThread.Name, random.Value.Next()); 
       } 

      } 

但是,我想隨機數在0和100之間?這可能嗎?

+0

「這可能嗎?」我想你已經試圖運行你的代碼或?=!結果是什麼? –

+0

@MongZhu,['Random.Next()'](https://msdn.microsoft.com/en-us/library/9b3ta19y(V = vs.110)的.aspx)可以返回更大的值(多達[INT .MaxValue](https://msdn.microsoft.com/en-us/library/system.int32.maxvalue(v = vs.110)的.aspx))。 – Sinatr

+0

是的,它會生成一個6位數的數字。我想0和100 –

回答

0

不知道你的要求是什麼...考慮更多的東西一樣:

class Program 
{ 

    static int counter = 0; 

    static readonly ThreadLocal<Random> random = 
     new ThreadLocal<Random>(() => new Random(Interlocked.Increment(ref counter))); 

    static List<Thread> players = new List<Thread>(); 

    static void Main(string[] args) 
    { 
     string[] playerNames = {"David", "James", "Mike" }; 
     foreach(string name in playerNames) 
     { 
      Thread T = new Thread(new ThreadStart(PlayerShot)); 
      T.Name = name; 
      players.Add(T); 
     } 

     Console.WriteLine("Waiting for Players to Shoot...\n"); 
     foreach (Thread player in players) 
     { 
      player.Start(); 
     } 

     // wait for all players to be done shooting 
     foreach (Thread player in players) 
     { 
      player.Join(); 
     } 

     Console.Write("\nPress [Enter] to quit."); 
     Console.ReadLine(); 
    } 

    public static void PlayerShot() 
    { 
     try 
     { 
      for (int i = 0; i < 3; i++) 
      { 
       System.Threading.Thread.Sleep(TimeSpan.FromSeconds(random.Value.Next(3, 11))); // 3 to 10 (INCLUSIVE) Second Delay between shots 
       Console.WriteLine("{0} shot {1}\n", Thread.CurrentThread.Name, random.Value.Next(0, 101)); // 0 to 100 (INCLUSIVE) 
      } 
     } 
     catch (Exception ex) { } 
    } 

} 
相關問題