C#,多线程死锁很容易哦

原文写于:2008-02-04

    这几天在看C#多线程的东东,确保多个线程不死锁是比较难的,但要死锁很容易。试着写了段死锁的代码,见下文。
    环境:.NET 2.0
    基本思路:学OS时的经典问题,两个线程抢占两个资源,线程1抢到了资源A,还需要资源B;线程2抢到了资源B,还需要资源A;结果就死锁了。 
 1  using System;
 2  using System.Collections.Generic;
 3  using System.Text;
 4  using System.Threading;
 5     
 6  namespace MultiThreadTest
 7  {
 8        class Program
 9     {
10            static void Main(string[] args)
11        {
12      Deadlock
20            }

21     
23        }

24    
25        class Deadlock
26       {
27            object locker1 = new object();
28            object locker2 = new object();
29            string s1="StartFromLocker1", s2="StartFromLocker2";
30            string l1 = "locker1", l2 = "locker2";
31     
32            public void StartFromLocker1()
33           {
34                lock(locker1)
35               {
36                    Console.WriteLine("{0} got {1}", s1, l1);
37                    Thread.Sleep(500);
38                    Console.WriteLine("{0} waiting for {1}", s1, l2);
39                    lock(locker2)
40                    {
41                        Console.WriteLine("{0} got {1}", s1, l2);
42                        Thread.Sleep(500);
43                    }

44                }

45                Console.WriteLine("leaving {0}", s1); 
46            }

47     
48            public void StartFromLocker2()
49           {
50                lock (locker2)
51               {
52                    Console.WriteLine("{0} got {1}", s2, l2);
53                   Thread.Sleep(500);
54                    Console.WriteLine("{0} waiting for {1}", s2, l1);
55                    lock (locker1)
56                   {
57                        Console.WriteLine("{0} got {1}", s2, l1);
58                        Thread.Sleep(500);
59                    }

60                }

61                Console.WriteLine("leaving {0}", s2); 
62            }

63        }
;
64   }
     运行结果:
StartFromLocker1 got locker1
StartFromLocker2 got locker2
StartFromLocker1 waiting for locker2
StartFromLocker2 waiting for locker1
 
posted @ 2008-05-02 22:12  ols  阅读(3336)  评论(2编辑  收藏  举报