用Monitor同步线程来演示妈妈做菜小明偷吃的实例

View Code
1 class Program
2 {
3 private static object obj = new object();
4
5 static void Main(string[] args)
6 {
7 Console.WriteLine(" ---**-用Monitor同步线程来演示妈妈做菜小明偷吃的实例**----");
8 Thread mother = new Thread(delegate()
9 {
10 for (int i = 1; i < 10; i++)
11 {
12
13 lock (obj)
14 {
15
16 Console.WriteLine("妈妈已经做好第{0}道菜了", i);
17
18 //Pulse方法就像是闹钟一样,提示别的进程可以访问独占琐了。
19
20 Monitor.Pulse(obj);
21
22 //当唤醒其余的线程之后,则自己在琐旁边打盹,知道被闹钟叫醒为止
23
24 Monitor.Wait(obj);
25
26 }
27 }
28
29 });
30
31
32
33 Thread xiaoming = new Thread(delegate()
34 {
35
36 for (int i = 1; i < 10; i++)
37 {
38
39 lock (obj)
40 {
41 Console.WriteLine("我正在偷吃第{0}道菜", i);
42
43 //Pulse方法就像是闹钟一样,提示别的进程可以访问独占琐了。
44
45 Monitor.Pulse(obj);
46
47 //当唤醒其余的线程之后,则自己在琐旁边打盹,知道被闹钟叫醒为止
48
49 Monitor.Wait(obj);
50
51 }
52 }
53 });
54
55 mother.Start();
56 xiaoming.Start();
57 Console.Read();
58 }
59
60 }

posted on 2011-02-18 19:39  人在程序  阅读(299)  评论(0编辑  收藏  举报

导航