//方式一,写交替死锁,Test1,Test2不会被输出 using System.Threading; using System; public static class Program { static object obj1 = new object(); static object obj2 = new object(); static void Main() { Thread thread1 = new Thread(Test1); Thread thread2 = new Thread(Test2); thread1.Start(); thread2.Start(); Console.WriteLine("Run"); Thread.Sleep(int.MaxValue); } static void Test1() { lock (obj1)//update obj1 set a=1 where id=1; { Thread.Sleep(100); lock (obj2)//update obj2 set b=1 where id=1; { Thread.Sleep(100); } } Console.WriteLine("Test1"); } static void Test2() { lock (obj2)//update obj2 set b=1 where id=1; { Thread.Sleep(100); lock (obj1)//update obj1 set a=1 where id=1; { Thread.Sleep(100); } } Console.WriteLine("Test2"); } } //方式二,读写交替死锁,Test1,Test2不会被输出 using System.Threading; using System; public static class Program { static ReaderWriterLock lock1 = new ReaderWriterLock(); static ReaderWriterLock lock2 = new ReaderWriterLock(); static void Main() { Thread thread1 = new Thread(Test1); Thread thread2 = new Thread(Test2); thread1.Start(); thread2.Start(); Console.WriteLine("Run"); Thread.Sleep(int.MaxValue); } static void Test1() { lock1.AcquireReaderLock(-1);//select a from obj1 where id=1; Thread.Sleep(100); lock2.AcquireWriterLock(-1);//update obj2 set b=1 where id=1; Thread.Sleep(100); lock2.ReleaseWriterLock(); lock1.ReleaseReaderLock(); Console.WriteLine("Test1"); } static void Test2() { lock2.AcquireReaderLock(-1);//select b from obj2 where id=1; Thread.Sleep(100); lock1.AcquireWriterLock(-1);//update obj1 set a=1 where id=1; Thread.Sleep(100); lock1.ReleaseWriterLock(); lock2.ReleaseReaderLock(); Console.WriteLine("Test2"); } }