寫了個會引起死鎖的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("沒出現這句話表示死鎖了");
}
}
}