您的位置:首页 > 编程语言 > C#

c#使用wait(),pulse()实现线程通信

2010-02-22 21:24 369 查看
例子1

线程在初暂时中断运行时调用Wait()方法,这使得些线程暂时进入休眠状态并释放对象的锁以允许其它线程使用此对象,然后,当其它线程使用完锁对象调用Pulse()或PulseAll()时,唤醒休眠的线程。Pulse()被调用时将恢复等待锁的线程队列的第一个线程,而调用PulseAll表示将锁释放给所有正在等待的线程。

using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
namespace ConsoleApplication1
{
class TickTock {
public void tick(bool running)
{
lock (this)
{
if (!running) {
Monitor.Pulse(this);
return;
}
Console.Write("Tick ");
Monitor.Pulse(this);
Monitor.Wait(this);
}
}

public void tock(bool running)
{
lock (this)
{
if (!running)
{
Monitor.Pulse(this);
return;
}
Console.WriteLine("Tock");
Monitor.Pulse(this);
Monitor.Wait(this);
}
}
}
class MyThread
{
public Thread thrd;
TickTock ttOb;
public MyThread(string name, TickTock tt)
{
thrd = new Thread(this.run);
ttOb = tt;
thrd.Name = name;
thrd.Start();
}
void run()
{
if (thrd.Name == "Tick")
{
for (int i = 0; i < 5; i++)
{
ttOb.tick(true );
}
ttOb.tick(false);
}
else
{
for (int i = 0; i < 5; i++) ttOb.tock(true);
ttOb.tock(false);
}
}
}
class Program
{
static void Main(string[] args)
{
TickTock tt = new TickTock();
MyThread mt1 = new MyThread("Tick", tt);
MyThread mt2 = new MyThread("Tock", tt);
mt1.thrd.Join();
mt2.thrd.Join();
Console.WriteLine("Clock Stopped");
Console.Read();
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: