C#死锁案例代码
简介:
如下代码实现创建两个线程t1和t2,分别起初分配占用lock1和ock2资源。当一个线程t1占用资源lock1时,再去请求另外一个资源lock2时,此时由于另外一个线程t2在正占用资源t2,请求失败,等待释放资源。同时t2又发出请求资源lock1,但是lock1又被t1占用,没有释放,也只能进行等待。此时两个线程只能等待一直等待对方释放资源,这就称之为死锁。
namespace Deadlock { class DL { int field1 = 0; int field2 = 0; private object lock1 = new int[1]; private object lock2 = new int[1]; public void First(int val) { lock (lock1) { Console.WriteLine("First: Acquired lock 1: " + Thread.CurrentThread.GetHashCode() + " Now Sleeping."); //Try commenting Thread.Sleep() Thread.Sleep(1000);//此时t2线程占用资源 Console.WriteLine("First: Acquired lock 1: " + Thread.CurrentThread.GetHashCode() + " Now wants lock2."); //当请求锁lock2时,lock被t2线程占用,等待释放 lock (lock2) { Console.WriteLine("First: Acquired lock 2: " + Thread.CurrentThread.GetHashCode()); field1 = val; field2 = val; } } } public void Second(int val) { lock (lock2) { Console.WriteLine("Second: Acquired lock 2: " + Thread.CurrentThread.GetHashCode()); //当请求锁lock1时,lock1被t1线程占用,等待释放 lock (lock1) { Console.WriteLine("Second: Acquired lock 1: " + Thread.CurrentThread.GetHashCode()); field1 = val; field2 = val; } } } } public class MainApp { DL d = new DL(); public static void Main() { MainApp m = new MainApp(); Thread t1 = new Thread(new ThreadStart(m.Run1)); t1.Start(); Thread t2 = new Thread(new ThreadStart(m.Run2)); t2.Start(); Console.ReadLine(); } public void Run1() { this.d.First(10); } public void Run2() { this.d.Second(10); } } }