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!

  • 相关阅读:
    0929作业
    0909上机作业
    熟悉的LINUX操作
    博客搭建成功啦!
    感谢管理员,通过了我的博客邀请。哈哈
    Asp.net常用的51个代码(非常实用)
    CSS命名规范:
    常用的JavaScript验证正则表达式
    Linq to sql 查询句法
    Web.config配置文件详解
  • 原文地址:https://www.cnblogs.com/javaleon/p/3919703.html
Copyright © 2011-2022 走看看