c#死锁示例代码

时间:2021-11-30 20:50:52
void Main()
{
    object obj1 = new object();
    object obj2 = new object();
    
    var t1 = new Thread(delegate(object p)
    {
        lock(obj1)
        {
            Thread.Sleep(5000);
            lock(obj2)
            {
                Console.WriteLine("Thread1 executed.");
            }
        }
    });
    
    t1.Start();
    
    
    var t2 = new Thread(delegate(object p)
    {
        lock(obj2)
        {
            Thread.Sleep(5000);
            lock(obj1)
            {
                Console.WriteLine("Thread2 executed.");
            }
        }
    });
    
    t2.Start();
    
    t1.Join();
    t2.Join();
    
    Console.WriteLine("over");
}