+ -
当前位置:首页 → 问答吧 → 请问,多线程Monitor类

请问,多线程Monitor类

时间:2011-12-06

来源:互联网

public class Program
  {
  static object ball = new object();
  public static void Main()
  {
  Thread threadPing = new Thread(ThreadPingProc);
  Thread threadPong = new Thread(ThreadPongProc);
  threadPing.Start();
  threadPong.Start();
  }
  static void ThreadPongProc()
  {
  lock (ball)
  {
  for (int i = 0; i < 5; i++)
  {
  System.Console.WriteLine("ThreadPong: Pong ");  
  Monitor.Pulse(ball);
  Monitor.Wait(ball);
  }
  }
  }
  static void ThreadPingProc()
  {
  lock (ball)
  {
  for (int i = 0; i < 5; i++)
  {
  System.Console.WriteLine("ThreadPing: Ping ");  
  Monitor.Pulse(ball);
  Monitor.Wait(ball);
  }
  }
  }
  }

我的问题是:
Lock关键字不是有获取锁、释放锁的功能吗?不是封装了try...finally语句吗?
对象锁释放后,队列线程自然就获得了对象锁,为什么还需要执行Pulse方法通知其他线程呢?

作者: ersrcdwer1   发布时间: 2011-12-06

引用楼主 ersrcdwer1 的回复:
...为什么还需要执行Pulse方法通知其他线程呢

如果没有Monitor.Pulse,那么lock下的循环就会执行到底,然后才退出lock。
也就是说5个"ThreadPong: Pong"或5个"ThreadPing: Ping "会连续出现。

而Monitor.Pulse则暂时交出控制权,使得Ping和Pong可能混合着出现。

作者: gomoku   发布时间: 2011-12-06

不知道你用lock还用moniter是什么意思

作者: bdmh   发布时间: 2011-12-06

引用 1 楼 gomoku 的回复:
引用楼主 ersrcdwer1 的回复:
...为什么还需要执行Pulse方法通知其他线程呢

如果没有Monitor.Pulse,那么lock下的循环就会执行到底,然后才退出lock。
也就是说5个"ThreadPong: Pong"或5个"ThreadPing: Ping "会连续出现。

而Monitor.Pulse则暂时交出控制权,使得Ping和Pong可能混合着出现。

+1

其实用lock 的地方 都应该换成 Monitor

用它的重载方法

作者: Sandy945   发布时间: 2011-12-06

引用 2 楼 bdmh 的回复:
不知道你用lock还用moniter是什么意思

我是网上摘抄的

作者: ersrcdwer1   发布时间: 2011-12-06

我觉得
Monitor.Pulse(ball);
  Monitor.Wait(ball);
完全没必要,多余

作者: ohkuy   发布时间: 2011-12-06

或者使用[MethodImpl(MethodImplOptions.Synchronized)]特性
C# code

  [MethodImpl(MethodImplOptions.Synchronized)]
  static void ThreadPongProc()
  {  
      for(int i = 0; i < 5; i++)
      {
          System.Console.WriteLine("ThreadPong: Pong ");   
  
      }
  }

作者: ohkuy   发布时间: 2011-12-06

引用 6 楼 ohkuy 的回复:

或者使用[MethodImpl(MethodImplOptions.Synchronized)]特性
C# code

[MethodImpl(MethodImplOptions.Synchronized)]
static void ThreadPongProc()
{
for(int i = 0; i < 5; i++)
{
Sy……

 [MethodImpl(MethodImplOptions.Synchronized)]啥东西?
没看到过这种写法呢

作者: ersrcdwer1   发布时间: 2011-12-06

那叫特性.
上面的Monitor都可以去掉.
直接用lock就可以了.

作者: enter89   发布时间: 2011-12-06