码迷,mamicode.com
首页 > 其他好文 > 详细

System.Threading.Monitor的使用

时间:2014-08-18 17:47:52      阅读:163      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   使用   os   io   for   ar   

 1 class Target
 2     { 
 3     }
 4     class Synchronization
 5     {
 6         
 7         public static void MonitorTest()
 8         {
 9             Target target = new Target();
10             for (int i = 0; i < 10; i++)
11             {
12                 System.Threading.ThreadPool.QueueUserWorkItem(new System.Threading.WaitCallback(work), target);
13             }
14 
15             System.Threading.ThreadPool.QueueUserWorkItem((t) => { Synchronization.signalWork(t); },target);
16         }
17 
18         public static void work(object state)
19         {
20             Target t = (Target)state;
21             Console.WriteLine(System.Threading.Thread.CurrentThread.ManagedThreadId.ToString() + " is waiting for enter!");
22             System.Threading.Monitor.Enter(t);
23             System.Threading.Monitor.Wait(t);
24             System.Threading.Monitor.Exit(t);
25             Console.WriteLine(System.Threading.Thread.CurrentThread.ManagedThreadId.ToString() + " is exited!");
26         }
27 
28         public static void signalWork(object t)
29         {
30             System.Threading.Monitor.Enter(t);
31             System.Threading.Monitor.Pulse(t);//发出一个通知
32             System.Threading.Monitor.PulseAll(t);//向所有等待线程发出通知
33             System.Threading.Monitor.Exit(t);
34         }
35     }

运行结果:

11 is waiting for enter!
10 is waiting for enter!
12 is waiting for enter!
13 is waiting for enter!
14 is waiting for enter!
15 is waiting for enter!
16 is waiting for enter!
17 is waiting for enter!
18 is waiting for enter!
19 is waiting for enter!
11 is exited!
12 is exited!
10 is exited!
13 is exited!
15 is exited!
16 is exited!
18 is exited!
19 is exited!
14 is exited!
17 is exited!

System.Threading.Monitor的使用,布布扣,bubuko.com

System.Threading.Monitor的使用

标签:style   blog   color   使用   os   io   for   ar   

原文地址:http://www.cnblogs.com/javaleon/p/3919703.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!