.NET平台下的管程类
来源:互联网 发布:成仓猝莫知所救 编辑:程序博客网 时间:2024/05/10 07:19
这周帮老师做了一个介绍管程的PPT,很多书在讲操作系统中线程的管程时,都有标注上说,管程比较偏学术,没有哪个语言支持,像我的老师就问了很多同事,大家都不知道其实.NET平台已经实现了管程类来帮助我们管理线程。以下我用C#语言作为例子,来简单介绍一下。如果有哪位高手更加了解这个类,希望您可以多讲解一下,如果发现错误请提出!!非常感激~
注[3]:在C# 2.0中,Monitor.Enter()和Monitor.Exit()调用间要try/finally来保护,否则可能会导致一个Monitor.Exit()永远不会被调用的异常。
using System.Threading;
{
class UsingMonitor
{
private int sum = 0;
private int output = 0;
{
Thread Doperation = new Thread(new ThreadStart(DataHandle));
Thread Dprint = new Thread(new ThreadStart(Dataprint));
Dprint.Name = "print thread";
Doperation.Start();
Doperation.Join();
Dprint.Join();
}
{
Monitor.Enter(this);
for (int i = 0; i < 20; i++)
{
if (output == 10)
{
Monitor.Wait(this);//handle thread释放资源,进入等待列队
}
output++;
Console.WriteLine(Thread.CurrentThread.Name + " is handling the" + output + " data.");
Thread.Sleep(1000);
if (output == 10)
{
Monitor.Pulse(this);//handle thread 中的资源被释放,叫醒等待列队中的第一个线程。
Console.WriteLine();
}
}
void Dataprint()
{
Monitor.Enter(this);
do
{
if (output == 0)
{
Monitor.Wait(this);//print thread释放资源,进入等待列队
}
Console.WriteLine(Thread.CurrentThread.Name + " is printint the" + output + " data.");
Thread.Sleep(1000);
output--;
sum++;
Console.WriteLine("/t the totle of data:" + sum);
if (output == 0)
{
Monitor.Pulse(this););//print thread 中的资源被释放,叫醒等待列队中的第一个线程。
Console.WriteLine();
}
} while (sum < 20);
Monitor.Exit(this);
static void main()
{
UsingMonitor myUM = new UsingMonitor ();
myUM.StartThread();
Console .Write ("end");
Console .ReadLine();
}
}
}
执行结果:
Data handle thread is handling the 1 data.
…….
Data handle thread is handling the 10 data.
Data printe thread is printing the 10 data. The totle of data:1
…….
Data printe thread is printing the 1 data. The totle of data:10
…….
Data handle thread is handling the 1 data.
…….
Data handle thread is handling the 10 data.
Data printe thread is printing the 10 data. The totle of data:11
…….
Data printe thread is printing the 1 data. The totle of data:20
end
参考资料:
[1]《C# Programmer’s Reference》
清华大学出版社
[2]《Visual C# 范例精要解析》吕高旭 编著
清华大学出版社
[3] 《Essential C# 2.0》 Mark Michealis著
人们邮电出版社
- .NET平台下的管程类
- NET 平台下的WebService
- .Net平台下的SqlHelper
- 管程的通俗理解
- 管程的特点
- 管程的思考
- 管程的理解
- 管程
- 管程
- 管程
- 管程
- 管程
- 管程
- 管程
- 管程
- 管程
- 管程
- 管程
- [转]在一个工程中添加别的工程的中已创建好的对话框资源。
- 现状
- 关于|Image$$RO$$Limit|等符号的意义(维库)
- ARM IMPORT |Image$$RO$$Limit| 的含义(21IC)
- 基于ARM的C语言运行环境初始化
- .NET平台下的管程类
- 学语言真累啊
- 学习网站
- 配置题目总结
- U盘文件夹都变成同名的exe文件的处理办法
- Velocity中如何判断null
- 新来的
- iugg
- 知道我不要你给我说对不起的原因吗?