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();
Console.ReadKey();
}
static void ThreadPingProc()
{
lock (ball)
{
for (int i = 0; i < 5; i++)
{
System.Console.WriteLine("张三 ");
Monitor.Wait(ball);
}
}
}
static void ThreadPongProc()
{
lock (ball)
{
for (int i = 0; i < 5; i++)
{
System.Console.WriteLine("李四 ");
Monitor.Pulse(ball);
}
}
}
}
两个问题:
1:首先执行 threadPing.Start();所以,无论如何,第一句都该是"张三"吧,可为什么多执行几次,第一句有时候是"李四"
2:
MSDN说的,
Pulse、PulseAll 和 Wait 方法必须从同步的代码块内调用。 此话怎讲?我上面的代码似乎就没有这样,没报错呢?