EventWaitHandle 用法

 1     //class Program
 2     //{
 3     //    static EventWaitHandle[] ewhs;
 4     //    static void UserResource(object o)
 5     //    {
 6     //        int i = (int)o;
 7     //        ewhs[i].WaitOne();
 8     //        Console.WriteLine("get resource" + Thread.CurrentThread.Name);
 9     //        Thread.Sleep(2000);
10     //        if (i + 1 < ewhs.Length)
11     //        {
12     //            ewhs[i + 1].Set(); //开启下一个线程的信号
13     //        }
14     //    }
15 
16     //    static void Main(string[] args)
17     //    {
18     //        int threadNum = 5;
19     //        ewhs = new EventWaitHandle[threadNum]; //信号灯数组,用于分别控制多个线程的执行
20 
21     //        Thread[] threads = new Thread[threadNum];
22     //        for (int i = 0; i < threadNum; i++)
23     //        {
24     //            string name = "ewh" + i.ToString();
25     //            //EventWaitHandle ewh = new EventWaitHandle(false, EventResetMode.AutoReset, name);     //默认信号灯都为没有信号
26     //            EventWaitHandle ewh = new EventWaitHandle(false, EventResetMode.ManualReset, name);     //默认信号灯都为没有信号
27     //            ewhs[i] = ewh;
28 
29     //            threads[i] = new Thread(new ParameterizedThreadStart(UserResource));
30     //            threads[i].Name = "threads" + i.ToString();
31     //            threads[i].Start(i);
32     //        }
33     //        ewhs[0].Set(); //开启第一个线程的信号,使其开始执行,其他线程阻塞。
34     //        Console.Read();
35     //    }
36     //}
37 
38     class Program
39     {
40         static EventWaitHandle ewhs;
41         static void UserResource()
42         {
43             ewhs.WaitOne();
44             Console.WriteLine("get resource" + Thread.CurrentThread.Name);
45             Thread.Sleep(2000);
46 
47             ewhs.Set();//再次开启一个线程的信号,使其开始执行,其他线程阻塞。
48         }
49 
50         static void Main(string[] args)
51         {
52             int threadNum = 5;
53             ewhs = new EventWaitHandle(false, EventResetMode.AutoReset, "eventWaitHandle"); //信号灯,用于分别控制多个线程的执行
54 
55             Thread[] threads = new Thread[threadNum];
56             for (int i = 0; i < threadNum; i++)
57             {
58                 string name = "ewh" + i.ToString();
59 
60                 threads[i] = new Thread(new ThreadStart(UserResource));
61                 threads[i].Name = "threads" + i.ToString();
62                 threads[i].Start();
63             }
64             ewhs.Set(); //开启一个线程的信号,使其开始执行,其他线程阻塞。
65             Console.Read();
66         }
67     }

 

posted on 2013-03-27 10:48  JackSlaterYu  阅读(254)  评论(0)    收藏  举报