C# 死锁

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace Demon
{
    class Program
    {
        private static object obj1 = new object();
        private static object obj2 = new object();
        private static int count = 0;
        static void Main()
        {
            Thread T1 = new Thread(Thread1);
            Thread T2 = new Thread(Thread2);
            T1.Start();
            T2.Start();
            while (true)
            {
              
                Console.WriteLine("dead lock! count:{0}", count);
            }
        }
        private static void Thread1()
        {
            while (true)
            {
                Monitor.Enter(obj1);   //先锁obj2,参数为对象,如果是值类型则需要装箱
                Monitor.Enter(obj2);//再锁obj1
                count++;
                Monitor.Exit(obj1);  //释放锁不存在先后关系
                Monitor.Exit(obj2);
            }
        }
        private static void Thread2()
        {
            while (true)
            {
                Monitor.Enter(obj1);  //先锁obj1
                Monitor.Enter(obj2);
                count++;
                Monitor.Exit(obj1);
                Monitor.Exit(obj2);
            }
        }
    }
}

原文地址:https://www.cnblogs.com/zztong/p/6695203.html