📄 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 + -