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的使用
时间: 2024-10-09 15:44:28