死锁的例子

        static object locker1 = new object();
        static object locker2 = new object();


        static void Main(string[] args)
        {

            var taskList = new Task[2];
            taskList[0] = Task.Run(() =>
            {
                Console.WriteLine("线程1 id:" + Thread.CurrentThread.ManagedThreadId);
                Console.WriteLine("线程1准备获取锁1");
                lock (locker1)
                {
                    Console.WriteLine("线程1获取了锁1");
                    Thread.Sleep(3000);

                    Console.WriteLine("线程1准备获取锁2");
                    lock (locker2)
                    {
                        Console.WriteLine("线程1获取了锁2");
                    }
                }

            });
            taskList[1] = Task.Run(() =>
            {
                Console.WriteLine("线程2 id:" + Thread.CurrentThread.ManagedThreadId);
                Console.WriteLine("线程2准备获取锁2");
                lock (locker2)
                {
                    Console.WriteLine("线程2获取了锁2");
                    Thread.Sleep(3000);

                    Console.WriteLine("线程2准备获取锁1");
                    lock (locker1)
                    {
                        Console.WriteLine("线程2获取了锁1");
                    }
                }

            });

            var finished = Task.WaitAll(taskList, 1000 * 10);
            if (finished)
            {
                Console.WriteLine("没有发生死锁");
            }
            else
            {
                Console.WriteLine("发生了死锁");
            }

            Console.ReadLine();
        }

  

死锁的例子

上一篇:HashMap中存储原理简单介绍


下一篇:Redis主从复制