线程二(Monitor)

Monitor 类的命名空间是 System.Threading,它的用法和 lock 本质是一样的。

  使用 Monitor 类锁定资源的代码如下。

  Monitor.Enter(object);
  try
  {
      //临界区代码
  }
  finally
  {
      Monitor.Exit(object);
  }

  在这里,object 值与 lock 中的 object 值是一样的。

  简而言之,lock 的写法是 Monitor 类的一种简写。

  public void PrintOdd1()
  {
    try
    {
      Monitor.Enter(obj);
      for (int i = 1; i <= 100; i += 2)
      {
        WriteLine(i);
      }

    }
    catch (Exception)
    {

      throw;
    }
    finally

     {
      Monitor.Exit(obj);
    }
  }

  public void PrintEven1()
  {
    try
    {
      Monitor.Enter(obj);
      for (int i = 2; i <= 100; i += 2)
      {
        WriteLine(i);
      }
    }
    catch (Exception)
    {

      throw;
    }
    finally
    {
      Monitor.Exit(obj);
    }
  }

  Program program = new Program();
  Thread t1 = new Thread(program.PrintOdd1);
  t1.Start();
  Thread t2 = new Thread(program.PrintEven1);
  t2.Start();

  另一个购票的例子:

  private object obj = new object();
  private static int ticketsNum = 100;

  public void BuyTickets1()
  {
    try
    {
      Monitor.Enter(obj);
      if (ticketsNum > 0)
      {
        ticketsNum -= 1;
        WriteLine("Thread1, 购1,剩" + ticketsNum);
      }
      else
      {
        WriteLine("Thread1, 没票了");
      }
    }
    catch (Exception)
    {
      throw;
    }
    finally
    {
      Monitor.Exit(obj);
    }
  }


  public void BuyTickets2()
  {
    try
    {
      Monitor.Enter(obj);
      if (ticketsNum > 0)
      {
        ticketsNum -= 1;
        WriteLine("Thread2, 购1,剩" + ticketsNum);
      }
      else
      {
        WriteLine("Thread2, 没票了");
      }
    }
    catch (Exception)
    {
      throw;
    }
    finally
    {
      Monitor.Exit(obj);
    }
  }

  static void Main(...)

  { 

    while (ticketsNum > 0)
    {
      Program program = new Program();
      Thread t1 = new Thread(program.BuyTickets1);
      t1.Start();
      Thread t2 = new Thread(program.BuyTickets2);
      t2.Start();
    }

  }

  以上模拟两个人购票,一个人购票时限制另一个人购票,同步更新剩余的票数。

  Monitor 类的用法虽然比 lock 关键字复杂,但其能添加等待获得锁定的超时值,这样就不会无限期等待获得对象锁。

  使用 TryEnter() 方法可以给它传送一个超时值,决定等待获得对象锁的最长时间。

  使用 TryEnter() 方法设置获得对象锁的时间的代码如下。

  Monitor.TryEnter(object, 毫秒数 );

  该方法能在指定的毫秒数内结束线程,这样能避免线程之间的死锁现象。

  此外,还能使用 Monitor 类中的 Wait() 方法让线程等待一定的时间,使用 Pulse() 方法通知处于等待状态的线程。

  

  http://c.biancheng.net/view/3000.html

原文地址:https://www.cnblogs.com/lu-yuan/p/11377584.html