然後在下面這個類MonitorSample的Main()函數中我們要做的就是建立兩個線程分別作為生產者和消費者,使用CellProd.ThreadRun()方法和CellCons.ThreadRun()方法對同一個Cell對象進行操作。
public class MonitorSample { public static void Main(String[] args) { int result = 0; file://一個標誌位,如果是0表示程式沒有出錯,如果是1表明有錯誤發生 Cell cell = new Cell( ); //下面使用cell初始化CellProd和CellCons兩個類,生產和消費次數均為20次 CellProd prod = new CellProd(cell, 20); CellCons cons = new CellCons(cell, 20); Thread producer = new Thread(new ThreadStart(prod.ThreadRun)); Thread consumer = new Thread(new ThreadStart(cons.ThreadRun)); //生產者線程和消費者線程都已經被建立,但是沒有開始執行 try { producer.Start( ); consumer.Start( ); producer.Join( ); consumer.Join( ); Console.ReadLine(); } catch (ThreadStateException e) { file://當線程因為所處狀態的原因而不能執行被請求的操作 Console.WriteLine(e); result = 1; } catch (ThreadInterruptedException e) { file://當線程在等待狀態的時候中止 Console.WriteLine(e); result = 1; } //儘管Main()函數沒有傳回值,但下面這條語句可以向父進程返回執行結果 Environment.ExitCode = result; } } |