class Program
{
static void Main(string[] args)
{
Thread thread1 = new Thread((ThreadStart)DLockSample.FunctionA);
Thread therad2 = new Thread((ThreadStart)DLockSample.FunctionB);
thread1.Start();
therad2.Start();
}
}
public class DLockSample
{
static object object1 = new object();
static object object2 = new object();
public static void FunctionA()
{
lock (object1)
{
Thread.Sleep(1000);
lock (object2)
{
Thread.Sleep(1000);
Console.WriteLine("heart beat - object2");
}
}
}
public static void FunctionB()
{
lock (object2)
{
lock (object1)
{
Thread.Sleep(1000);
Console.WriteLine("heart beat - object1");
}
}
} }
答案 0 :(得分:1)
始终在所有线程中以相同的顺序输入锁。另见hierarchy of critical sections I.e. FunctionB需要是:
public static void FunctionB()
{
lock (object1)
{
lock (object2)
...
答案 1 :(得分:1)
这是一个很容易解决的问题。只是一些提示: