C#的多線程機制探索6

來源:互聯網
上載者:User

  然後在下面這個類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;
  }
  }

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.