using System;
using System.Threading;
namespace MutexConsoleApp
{
class Program
{
public static Mutex mut = new Mutex();
private const int num_threads = 5;
private const int num_ideas = 3;
static void Main(string[] args)
{
Console.WriteLine("大魔神說....這次開會大家各提{0}個意見!",num_ideas);
Thread[] myThread = new Thread[num_threads];
for (int i = 1; i <= num_threads; i++)
{
myThread[i-1] = new Thread(new ThreadStart( MyThreadProc));
myThread[i-1].Name = String.Format("職員 {0} 號", i);
myThread[i-1].Start();
}
//等待每一位發言完畢
for (int i = 1; i <= num_threads; i++)
{
myThread[i - 1].Join();
}
//大魔神作總結 ^^~
Console.WriteLine();
Console.WriteLine("大魔神說....很好,大家的意見我會參考!", num_ideas);
Console.ReadLine();
}
private static void MyThreadProc()
{
//進入互斥區,搶得發言權,其他人只得等待
mut.WaitOne();
Console.WriteLine();
Console.WriteLine("{0} :大家不要吵,先聽我說!", Thread.CurrentThread.Name);
for (int i = 1; i <= num_ideas; i++)
{
Console.WriteLine("{0} :我得的第 {1} 個方案是‧‧‧※○◎●‧‧‧", Thread.CurrentThread.Name,i);
Thread.Sleep(500);
}
Console.WriteLine("{0} :好啦,我說完啦,下一位請發言!", Thread.CurrentThread.Name);
//離開互斥區,放棄發言權,下一個等待的人可以準備發言了
mut.ReleaseMutex();
}
}
}
歡迎光臨 Math Pro 數學補給站 (https://math.pro/db/) | 論壇程式使用 Discuz! 6.1.0 |