当前位置:编程学习 > C#/ASP.NET >>

一个会引起死锁的C#程序

写了个会引起死锁的C#程序,帮助理解死锁的含义:
 

using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;

namespace @lock
{
    class Program
    {
        public static object lock_A = new object();
        public static object lock_B = new object();
        public void DoSomething()
        {
           
            lock (lock_A)
            {
                Thread.Sleep(500);
                Console.WriteLine("我是lock_A,我想要lock_B");
                lock (lock_B)
                {
                    Console.WriteLine("没出现这句话表示死锁了");
                }
            }
        }

        static void Main()
        {
            Program a = new Program();
            Thread th = new Thread(new ThreadStart(a.DoSomething));
            th.Start();

            lock (lock_B) 
            {

                Console.WriteLine("我是lock_B,我想要lock_A");
                lock (lock_A)
                {
                    Console.WriteLine("没出现这句话表示死锁了");
                }
            }

            Console.WriteLine("没出现这句话表示死锁了");
        } 

    }
}
    
补充:软件开发 , C# ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,