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 (objec T 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); // sends a notification 32 system. threading. monitor. pulseall (t); // send a notification to all wait threads 33 system. threading. monitor. exit (t); 34} 35}
Running result:
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!