zoukankan      html  css  js  c++  java
  • 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!

  • 相关阅读:
    sass接触
    css 文字超出部分显示省略号(原)
    vue组件
    字节流
    File类、递归
    异常
    静态导入、可变参数、Collections集合工具类、集合嵌套
    Map接口
    Set接口
    List接口
  • 原文地址:https://www.cnblogs.com/javaleon/p/3919703.html
Copyright © 2011-2022 走看看