// Semaphore是System.Threading下的类,限制可同时访问某一资源或资源池的线程数。
1 using System;
2 using System.Threading;
3
4 namespace testSemaphore
5 {
6 //class Program
7 //{
8 // static Semaphore sema = new Semaphore(1, 2);
9
10 // static void Main(string[] args)
11 // {
12 // for (int i = 0; i < 300; i++)
13 // {
14 // var thread = new Thread(Test) { Name = string.Format("Thread{0}", i) };
15 // thread.Start();
16 // }
17 // Console.ReadKey();
18 // }
19
20
21 // static void Test()
22 // {
23 // sema.WaitOne();
24 // for (int i = 0; i < 3; i++)
25 // {
26 // Console.WriteLine(string.Format("ThreadName:{0} i:{1}", Thread.CurrentThread.Name, i));
27 // Thread.Sleep(1000);
28 // }
29 // sema.Release();
30 // Console.ReadKey();
31 // }
32 //}
33 class Program
34 {
35 //Semaphore(初始授予0个请求数,设置最大可授予5个请求数)
36 static Semaphore semaphore = new Semaphore(0, 5);
37
38 static void Main(string[] args)
39 {
40 for (int i = 1; i <= 5; i++)
41 {
42 Thread thread = new Thread(work);
43 thread.Start(i);
44 }
45
46 Thread.Sleep(1000);
47 Console.WriteLine("Main方法结束");
48
49 //授予5个请求
50 semaphore.Release(5);
51 Console.ReadLine();
52 }
53
54 static void work(object obj)
55 {
56 semaphore.WaitOne();
57 Console.WriteLine("print: {0}", obj);
58 semaphore.Release();
59 }
60 }
61 }