C# 死锁

来源:互联网 发布:紫砂壶店铺淘宝排名 编辑:程序博客网 时间:2024/05/29 09:47
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);            }        }    }}

0 0
原创粉丝点击