Monitor线程操作(当一个线程中处于等待状态时,另外一个线程来解锁它的等待状态继续执行下去)

代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace ConsoleApplication1
{
    class Program
    {
        static int x = 0;
        private static object _obj = new object();
        static void Main(string[] args)
        {
            for (int i = 0; i < 1; i++)
            {
                Thread thread = new Thread(new ThreadStart(test));
                thread.Start();
            }
            Thread.Sleep(2000);

            Thread thread1 = new Thread(new ThreadStart(test1));
            thread1.Start();
            Thread.Sleep(2000);
            Thread thread2 = new Thread(new ThreadStart(test));
            thread2.Start();
            Thread.Sleep(2000);
            Thread thread3 = new Thread(new ThreadStart(test3));
            thread3.Start();
            Console.ReadKey();
        }

        static void test()
        {
            try
            {
                Monitor.Enter(_obj);
                if (x > 0)
                {
                    Console.WriteLine("开始等待");
                    Monitor.Wait(_obj);
                 //   Monitor.Wait(_obj, 5000);这是我设置的等待5秒继续执行
                    Console.WriteLine("线程3释放了锁定对象,等待已结束,现在退出!");
                }
                x--;
                Console.WriteLine(x);
                Console.WriteLine(Thread.CurrentThread.ManagedThreadId.ToString());
            }
            catch (Exception ex)
            {
                throw;
            }
            finally
            {
                Monitor.Pulse(_obj);
                Monitor.Exit(_obj);
            }
        }

        static void test1()
        {
            x = 2;
        }

        static void test3()
        {
            Console.WriteLine("线程3进入,开始释放锁定对象!");
            Monitor.Enter(_obj);
            Monitor.Pulse(_obj);
            Monitor.Exit(_obj);
            Console.WriteLine("线程3已释放了锁定对象!");

        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值