Monitor线程操作(当一个线程中处于等待状态时,另外一个线程来解锁它的等待状态继续执行下去)
2015-08-26 10:09
393 查看
代码
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; namespace ConsoleApplication1 { class Program { static int x = 0; private static object _obj = new object(); static void Main(string[] args) { for (int i = 0; i < 1; i++) { Thread thread = new Thread(new ThreadStart(test)); thread.Start(); } Thread.Sleep(2000); Thread thread1 = new Thread(new ThreadStart(test1)); thread1.Start(); Thread.Sleep(2000); Thread thread2 = new Thread(new ThreadStart(test)); thread2.Start(); Thread.Sleep(2000); Thread thread3 = new Thread(new ThreadStart(test3)); thread3.Start(); Console.ReadKey(); } static void test() { try { Monitor.Enter(_obj); if (x > 0) { Console.WriteLine("开始等待"); Monitor.Wait(_obj); // Monitor.Wait(_obj, 5000);这是我设置的等待5秒继续执行 Console.WriteLine("线程3释放了锁定对象,等待已结束,现在退出!"); } x--; Console.WriteLine(x); Console.WriteLine(Thread.CurrentThread.ManagedThreadId.ToString()); } catch (Exception ex) { throw; } finally { Monitor.Pulse(_obj); Monitor.Exit(_obj); } } static void test1() { x = 2; } static void test3() { Console.WriteLine("线程3进入,开始释放锁定对象!"); Monitor.Enter(_obj); Monitor.Pulse(_obj); Monitor.Exit(_obj); Console.WriteLine("线程3已释放了锁定对象!"); } } }
相关文章推荐
- TCP 与 UDP
- malloc/free和new/delete的区别
- [MFC学习笔记]--lesson12 文件操作
- UIButton 点击传递两个参数的实现
- python+django+fastcgi+nginx
- 【华为OJ平台练习题】Ascii码排序
- ASCII编码 和 UNICODE编码
- PS学习笔记-----合并图层
- iOS沙盒目录中Documents, Library, tmp的作用和区别
- Android中Context详解 ---- 你所不知道的Context
- POJ3630——简单Trie树
- 复制xcode工程时 (error code -8085)
- sql之游标
- Android Studio 常用快捷键
- nginx实现web负载均衡
- 下架正在上架的app
- A missing vtable usually means the first non-inline virtual member function has no definition
- ubuntu 安装简单php环境(不包含mysql)
- 九之再续:教你一步一步用c语言实现sift算法、上
- ubuntu10.04安装交叉编译器