首页 > 代码库 > System.Threading.Monitor的使用
System.Threading.Monitor的使用
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!
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。