简单死锁

原理:线程A获取a上的锁,请求b上的锁,死锁等待b;线程B获取b上的锁,请求a上的锁,死锁等待a

    class Program
    {
        public static object objLockA = new object();
        public static object objLockB = new object();

        static void Main(string[] args)
        {
          //  ThreadStart start=
            Thread t1 = new Thread(Cw);
            t1.Start(1);
            Thread t2 = new Thread(Cw);
            t2.Start(0);
            Console.Read();
        }
        public static void Cw(object obj)
        {
            int i = Convert.ToInt32(obj);
            if (i == 0)
            {
                lock (objLockA)
                {
                    Thread.Sleep(1000 * 5);
                    lock (objLockB)
                    {
                        Console.WriteLine("BBBB");
                    }
                    Console.WriteLine("AAAA");
                }
            }
            else
            {
                lock (objLockB)
                {
                    Thread.Sleep(1000 * 5);
                    lock (objLockA)
                    {
                        Thread.Sleep(1000);
                    }
                    Console.WriteLine("BBBB");
                }
            }
        }
    }

 

你可能感兴趣的:(C#)