c#使用wait(),pulse()实现线程通信
2010-02-22 21:24
369 查看
例子1
线程在初暂时中断运行时调用Wait()方法,这使得些线程暂时进入休眠状态并释放对象的锁以允许其它线程使用此对象,然后,当其它线程使用完锁对象调用Pulse()或PulseAll()时,唤醒休眠的线程。Pulse()被调用时将恢复等待锁的线程队列的第一个线程,而调用PulseAll表示将锁释放给所有正在等待的线程。
线程在初暂时中断运行时调用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(); } } }
相关文章推荐
- C# Monitor的Wait和Pulse方法使用详解
- C# 线程手册 第三章 使用线程 Monitor.Wait() 和 Monitor.Pulse()
- 使用Thread的wait和notify方法实现线程通信
- 使用wait()与notify()实现线程间协作
- 使用C#代码实现增加用户帐号
- C#使用Object类实现栈的方法详解
- c#+Winform实现自定义的“复制、粘贴”右键快捷菜单,多个控件共享使用一个右键菜单
- 使用javascript ajax C#实现类似百度的搜索框效果
- C#使用Socket实现服务器与多个客户端通信(简单的聊天系统)
- 使用Tesseract (OCR)实现简单的验证码识别(C#)+窗体淡入淡出效果
- C#使用memcached实现缓存
- 观察者模式使用C#实现
- C#中使用Socket实现简单Web服务器
- 使用C#实现WGS84坐标转高德的火星坐标,数据源来自excel的两列,输出到excel中
- C#使用DataContractJsonSerializer实现Json格式的序列化和反序列化
- 在C#中使用异步Socket编程实现TCP网络服务的C/S的通讯构架(一)----基础类库部分
- [转]C#、VB.NET使用HttpWebRequest访问https地址(SSL)的实现
- 使用C#实现ADSL自动拨号
- ABB机器人上位机C#使用PC SDK搭配机器人程序实现自动化
- 在C#中使用异步Socket编程实现TCP网络服务的C/S的通讯构架(二)