线程等待例子,来自微软

线程等待例子

        private static AutoResetEvent event_1 = new AutoResetEvent(true);
        private static AutoResetEvent event_2 = new AutoResetEvent(false);
        static void ThreadProc()
        {
            string name = Thread.CurrentThread.Name;

            Console.WriteLine("{0} 等待自动复位事件# 1。 ", name);
            event_1.WaitOne();
            Console.WriteLine("{0} 从自动复位事件# 1发布。", name);

            Console.WriteLine("{0} 等待自动复位事件# 2。", name);
            event_2.WaitOne();
            Console.WriteLine("{0} 从自动复位事件# 2发布。", name);

            Console.WriteLine("{0} 结束.", name);
        }
        static void Main(string[] args)
        {
        起始:

            Console.WriteLine("按回车键创建三个线程,然后开始 .\r\n" +
                              "线程等待自动复位事件# 1,创建了 \r\n" +
                              "在信号状态,所以第一个线程被释放 .\r\n" +
                              "这使得自动复位事件# 1成无信号状态。 ");
            Console.ReadLine();

            for (int i = 1; i < 4; i++)
            {
                Thread t = new Thread(ThreadProc);
                t.Name = "Thread_" + i;
                t.Start();
            }
            Thread.Sleep(250);

            for (int i = 0; i < 2; i++)
            {
                Console.WriteLine("按回车键释放另一个线程。 ");
                Console.ReadLine();
                event_1.Set();
                Thread.Sleep(250);
            }

            Console.WriteLine("\r\n所有的线程正在等待自动复位事件# 2。 ");
            for (int i = 0; i < 3; i++)
            {
                Console.WriteLine("按回车键释放一个线程。 ");
                Console.ReadLine();
                event_2.Set();
                Thread.Sleep(250);
            }
       }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值