下面定義生產者類 CellProd 和消費者類 CellCons
public class CellProd
{
Cell cell; // 被操作的Cell對象
int quantity =
public CellProd(Cell box
{
//構造函數
cell = box;
quantity = request;
}
public void ThreadRun( )
{
for(int looper=
cell
}
}
public class CellCons
{
Cell cell;
int quantity =
public CellCons(Cell box
{
//構造函數
cell = box;
quantity = request;
}
public void ThreadRun( )
{
int valReturned;
for(int looper=
valReturned=cell
}
}
然後在下面這個類MonitorSample的Main()函數中
public class MonitorSample
{
public static void Main(String[] args)
{
int result =
Cell cell = new Cell( );
//下面使用cell初始化CellProd和CellCons兩個類
CellProd prod = new CellProd(cell
CellCons cons = new CellCons(cell
Thread producer = new Thread(new ThreadStart(prod
Thread consumer = new Thread(new ThreadStart(cons
//生產者線程和消費者線程都已經被創建
try
{
producer
consumer
producer
consumer
Console
}
catch (ThreadStateException e)
{
//當線程因為所處狀態的原因而不能執行被請求的操作
Console
result =
}
catch (ThreadInterruptedException e)
{
//當線程在等待狀態的時候中止
Console
result =
}
//盡管Main()函數沒有返回值
Environment
}
}
在上面的例程中
它的執行結果很簡單
Produce
Produce
事實上
From:http://tw.wingwit.com/Article/program/net/201311/15265.html