有趣的多线程编程(4)——死锁
有趣的多线程编程(4)——死锁 // DeadLockSample.cs
// 分析一下为什么会发生死锁?
Thread.Sleep(500); Console.WriteLine (); ); Console.WriteLine (); ); } Console.WriteLine (); } Console.WriteLine(); } ); ); Thread.Sleep(1000); Console.WriteLine(); ); } Console.WriteLine (); } Console.WriteLine(); }} Locking firstLock
Locked firstLock
Locking secondLock
Locked secondLock
Locking firstLock Locking secondLock
因应之道,使用Queue和Monitor:
//QueueMonitorThread.cs
, i); queue.Produce(i); Thread.Sleep(rng.Next(1000)); } } Random rng = , o); Thread.Sleep(rng.Next(1000)); } }}Producing 0 Consuming 0
Producing 1 Consuming 1
Producing 2 Consuming 2
Producing 3 Consuming 3
Producing 4
Producing 5 Consuming 4
Producing 6 Consuming 5
Consuming 6
Producing 7 Consuming 7
Producing 8 Consuming 8
Producing 9 Consuming 9