1 /// <summary> 2 /// 信号量Semaphore的使用-可以用来限制线程能运行的数量。 3 /// </summary> 4 class Program 5 { 6 //设置一个初始值设为0,最大允许1个线程允许的信号量 7 static Semaphore semaphore = new Semaphore(0, 1); 8 static void Main(string[] args) 9 { 10 for (int i = 1; i <= 5; i++) 11 { 12 Thread thread = new Thread(new ParameterizedThreadStart(work)); 13 thread.Start(i); 14 } 15 16 Thread.Sleep(2000); 17 Console.WriteLine("Main thread over!"); 18 19 //释放信号量 20 //Release()相当于是Release(1) 21 semaphore.Release(); 22 Console.ReadKey(); 23 } 24 25 static void work(object obj) 26 { 27 //当有线程释放时才会执行. 28 semaphore.WaitOne(); 29 Console.WriteLine("Thread {0} start!", obj); 30 //semaphore.Release(); //取消注释,其它线程就会继续执行 31 } 32 }