同步对象:Monitor
来源:互联网 发布:澳门网络博客755 编辑:程序博客网 时间:2024/06/07 20:32
using System;
using System.Threading;
public class Cell
{
int cellContents;
bool readerFlag = false;
public int ReadFromCell()
{
lock (this)
{
if (!readerFlag)
{
try
{
Monitor.Wait(this);
}
catch (SynchronizationLockException e)
{
Console.WriteLine(e);
}
catch (ThreadInterruptedException e)
{
Console.WriteLine(e);
}
}
Console.WriteLine("Consume: {0}", cellContents);
readerFlag = false;
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("Produce: {0}", cellContents);
readerFlag = true;
Monitor.Pulse(this);
}
}
}
public class CellProd
{
Cell 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 = cell.ReadFromCell();
}
}
public class MonitorSample
{
public static void Main(string[] args)
{
int result = 0;
Cell cell = new Cell();
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)
{
Console.WriteLine(e);
result = 1;
}
catch (ThreadInterruptedException e)
{
Console.WriteLine(e);
result = 1;
}
Environment.ExitCode = result;
}
}
- 同步对象:Monitor
- Monitor提供同步对象(笔记)
- 线程同步之Monitor
- 同步线程2(Monitor)
- 同步技术之Monitor
- c#线程同步系列(三) C# Monitor类锁定对象
- 线程同步lock and monitor
- C# 线程同步之Monitor
- c#线程同步(3)----monitor
- 同步代码区Monitor类的使用
- 线程同步作业(一):Lock,monitor
- 多线程同步之——monitor
- [Thread] 執行緒同步資源鎖定 – Monitor
- Android Screen Monitor同步手机屏幕到PC
- Android Screen Monitor同步手机屏幕到PC
- monitor
- Monitor
- Monitor
- [转载]JTable学习
- ActionScipt
- EEEE日常操作系统性能topas监控的说明
- php日历转农历的转换代码(转)
- linux挂载windows共享后,网站里的图片不能正常显示
- 同步对象:Monitor
- 一篇很好的AJAX入门教程
- 跨服务器远程链接 sql
- 修改http和https的端口号
- 重载操作符:Array:Overload Operator
- 连接数量满导致数据库连接不上问题
- kksfbc child completion事件导致cpu长时间不释放
- 吸血鬼数字 高效算法
- 空间插值方法总结