?? c9-06.cs
字號:
// 運用Monitor類同步線程示例
using System;
using System.Threading;
public class MonitorSample
{
public static void Main(String[] args)
{
// result=0表示沒有發生異常,為1則表示發生異常
int result = 0;
Cell cell = new Cell( );
CellProd prod = new CellProd(cell, 5);
CellCons cons = new CellCons(cell, 5);
// 創建producer和consumer線程
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( );
// 線程producer和consumer結束
}
catch (ThreadStateException e)
{
Console.WriteLine(e); // 顯示異常信息
result = 1;
}
catch (ThreadInterruptedException e)
{
// 顯示線程在等待的時候被中斷的異常
Console.WriteLine(e);
result = 1;
}
Environment.ExitCode = result;
}
}
public class CellProd
{
Cell cell; // 定義cell對象
// quantity變量表示cell中產品的數量
int quantity = 1;
public CellProd(Cell box, int request)
{
cell = box;
quantity = request;
}
public void ThreadRun( )
{
for(int looper=1; looper<=quantity; looper++)
cell.WriteToCell(looper);
}
}
public class CellCons
{
Cell cell;
int quantity = 1;
public CellCons(Cell box, int request)
{
cell = box;
quantity = request;
}
public void ThreadRun( )
{
int valReturned;
for(int looper=1; looper<=quantity; looper++)
// 在valReturned中保存消耗數量
valReturned=cell.ReadFromCell( );
}
}
public class Cell
{
int cellContents;
bool readerFlag = false;
public int ReadFromCell( )
{
lock(this) // 進入同步塊
{
if (!readerFlag)
{ // 等待直到Cell.WriteToCell處理完成
try
{
// 等待Monitor.Pulse
Monitor.Wait(this);
}
catch (SynchronizationLockException e)
{
Console.WriteLine(e);
}
catch (ThreadInterruptedException e)
{
Console.WriteLine(e);
}
}
Console.WriteLine("消耗: {0}",cellContents);
readerFlag = false;
// Pulse讓Cell.WriteToCell知道Cell.ReadFromCell已經完成
Monitor.Pulse(this);
} // 退出同步塊
return cellContents;
}
public void WriteToCell(int n)
{
lock(this) // 進入同步塊
{
if (readerFlag)
{
try
{
Monitor.Wait(this);
}
catch (SynchronizationLockException e)
{
Console.WriteLine(e);
}
catch (ThreadInterruptedException e)
{
Console.WriteLine(e);
}
}
cellContents = n;
Console.WriteLine("制造: {0}",cellContents);
readerFlag = true;
// Pulse讓Cell.ReadFromCell知道Cell.WriteToCell已經完成
Monitor.Pulse(this);
} // 退出同步塊
}
}
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -