c#多執行緒控制
阿新 • • 發佈:2018-11-29
class Program { static Thread SeekBookThread = new Thread(new ThreadStart(TestMutiThrd.SeekProc)); static Thread payMoneyThread = new Thread(new ThreadStart(TestMutiThrd.PayMoneyProc)); static Thread getBookThread = new Thread(new ThreadStart(TestMutiThrd.GetBookProc));static void Main(string[] args) { SeekBookThread.Name = "掃描執行緒"; SeekBookThread.Start(); payMoneyThread.Name = "付錢執行緒"; payMoneyThread.Start(); getBookThread.Name = "取書執行緒"; getBookThread.Start();for (int i = 1; i <= TestMutiThrd.numIterations; i++) { Console.WriteLine("買書執行緒:書本{0}", i); TestMutiThrd.number = i; //Signal that a value has been written. TestMutiThrd.SekEvent.Set();//解鎖掃描執行緒 TestMutiThrd.buyResetEvent.WaitOne();//等待買書所有執行緒執行結束,才能繼續 Thread.Sleep(0); } Thread.Sleep(1000); Console.ReadLine(); SeekBookThread.Abort(); payMoneyThread.Abort(); getBookThread.Abort(); } } public class TestMutiThrd { public const int numIterations = 50; //買書 public static AutoResetEvent buyResetEvent = new AutoResetEvent(false); //掃描 public static AutoResetEvent SekEvent = new AutoResetEvent(false); //付錢 public static AutoResetEvent PayEvent = new AutoResetEvent(false); //取書 public static AutoResetEvent GetEvent = new AutoResetEvent(false); //付錢和取書 public static ManualResetEvent PayGetEvent = new ManualResetEvent(false); public static ReaderWriterLock RWLock = new ReaderWriterLock(); //static ManualResetEvent myResetEvent = new ManualResetEvent(false); //static ManualResetEvent ChangeEvent = new ManualResetEvent(false); public static int number; //這是關鍵資源 public static TestMutiThrd OTestMutiThrd = new TestMutiThrd(); public int NumIterations { get { return numIterations; } } /// <summary> /// 掃描過程 /// </summary> public static void SeekProc() { while (true) //(thread.ThreadState != ThreadState.Aborted) { SekEvent.WaitOne(); //SekEvent.Reset(); Console.WriteLine("{0}:書本{1}", Thread.CurrentThread.Name, number); Thread.Sleep(0); PayEvent.Set();//解鎖付款執行緒 //PayGetEvent.Set();//同時解鎖付款和取書執行緒 } } /// <summary> /// 付錢過程 /// </summary> public static void PayMoneyProc() { while (true) { PayEvent.WaitOne(); Console.WriteLine("{0}:書本{1}", Thread.CurrentThread.Name, number); Thread.Sleep(10); GetEvent.Set();//解鎖取書執行緒 } } /// <summary> /// 取書過程 /// </summary> public static void GetBookProc() { while (true) { GetEvent.WaitOne(); Console.WriteLine("{0}:書本{1}", Thread.CurrentThread.Name, number); Console.WriteLine("------------------------------------------"); Thread.Sleep(10); buyResetEvent.Set();//解鎖買書執行緒 } } }