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方法通知其他线程呢?
{
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方法通知其他线程呢?
也就是说5个"ThreadPong: Pong"或5个"ThreadPing: Ping "会连续出现。而Monitor.Pulse则暂时交出控制权,使得Ping和Pong可能混合着出现。
Monitor.Pulse(ball);
Monitor.Wait(ball);
完全没必要,多余
static void ThreadPongProc()
{
for(int i = 0; i < 5; i++)
{
System.Console.WriteLine("ThreadPong: Pong ");
}
}
没看到过这种写法呢
上面的Monitor都可以去掉.
直接用lock就可以了.