2017-05-12 6 views
0

3つのスレッドを作成しようとしています。各スレッドはプレーヤーであり、3回のショットを持つ。ショットはスレッドからランダムに生成された番号です。私はこれを試しましたスレッドをランダムに生成された番号に設定するには

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) { } 
    } 

} 
関連する問題