请问,多线程Monitor类

ersrcdwer1 2011-12-06 03:36:17
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方法通知其他线程呢?
...全文
295 11 打赏 收藏 转发到动态 举报
写回复
用AI写文章
11 条回复
切换为时间正序
请发表友善的回复…
发表回复
Daqing 2011-12-06
  • 打赏
  • 举报
回复
用lock 就不要用monitor了,两个都是加锁,常用monitor,因为lock最后还是编译为monitor。
绿领巾童鞋 2011-12-06
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 gomoku 的回复:]

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

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

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

……
[/Quote]
++
阿非 2011-12-06
  • 打赏
  • 举报
回复
[Quote=引用 4 楼 ersrcdwer1 的回复:]
引用 2 楼 bdmh 的回复:
不知道你用lock还用moniter是什么意思

我是网上摘抄的
[/Quote]

你有没有看#1的回复
Waldenz 2011-12-06
  • 打赏
  • 举报
回复
那叫特性.
上面的Monitor都可以去掉.
直接用lock就可以了.
ersrcdwer1 2011-12-06
  • 打赏
  • 举报
回复
[Quote=引用 6 楼 ohkuy 的回复:]

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

[MethodImpl(MethodImplOptions.Synchronized)]
static void ThreadPongProc()
{
for(int i = 0; i < 5; i++)
{
Sy……
[/Quote]
[MethodImpl(MethodImplOptions.Synchronized)]啥东西?
没看到过这种写法呢
ohkuy 2011-12-06
  • 打赏
  • 举报
回复
或者使用[MethodImpl(MethodImplOptions.Synchronized)]特性

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

}
}
ohkuy 2011-12-06
  • 打赏
  • 举报
回复
我觉得
Monitor.Pulse(ball);
Monitor.Wait(ball);
完全没必要,多余
ersrcdwer1 2011-12-06
  • 打赏
  • 举报
回复
[Quote=引用 2 楼 bdmh 的回复:]
不知道你用lock还用moniter是什么意思
[/Quote]
我是网上摘抄的
阿非 2011-12-06
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 gomoku 的回复:]
引用楼主 ersrcdwer1 的回复:
...为什么还需要执行Pulse方法通知其他线程呢

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

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

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

用它的重载方法
bdmh 2011-12-06
  • 打赏
  • 举报
回复
不知道你用lock还用moniter是什么意思
gomoku 2011-12-06
  • 打赏
  • 举报
回复
[Quote=引用楼主 ersrcdwer1 的回复:]
...为什么还需要执行Pulse方法通知其他线程呢
[/Quote]
如果没有Monitor.Pulse,那么lock下的循环就会执行到底,然后才退出lock。
也就是说5个"ThreadPong: Pong"或5个"ThreadPing: Ping "会连续出现。

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

110,552

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧