乒乓球锁:Lock an Object:Switch Different Functions

来源:互联网 发布:linux下载jdk1.8 命令 编辑:程序博客网 时间:2024/05/21 16:48

using System.Threading;
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()
    {
        System.Console.WriteLine("ThreadPong: Hello!");
        lock (ball)
            for (int i = 0; i < 5; i++)
            {
                System.Console.WriteLine("ThreadPong: Pong ");
                Monitor.Pulse(ball);
                Monitor.Wait(ball);
            }
        System.Console.WriteLine("ThreadPong: Bye!");
    }
    static void ThreadPingProc()
    {
        System.Console.WriteLine("ThreadPing: Hello!");
        lock (ball)
            for (int i = 0; i < 5; i++)
            {
                System.Console.WriteLine("ThreadPing: Ping ");
                Monitor.Pulse(ball);
                Monitor.Wait(ball);
            }
        System.Console.WriteLine("ThreadPing: Bye!");
    }
}

原创粉丝点击