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之間?這可能嗎?
「這可能嗎?」我想你已經試圖運行你的代碼或?=!結果是什麼? –
@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
是的,它會生成一個6位數的數字。我想0和100 –