代码改变世界

限制线程的执行个数

2010-01-07 21:43  c#在路上  阅读(3201)  评论(0)    收藏  举报
限制只有三个线程能够执行
代码

using System;
using System.Threading;

namespace LimitThread
{
    
class Program
    {
        
static Semaphore semahoro=new Semaphore(3,3);
        
public static void Main(string[] args)
        {
            
for (int i=0;i<10 ;i++ ) {
                
new Thread(Work).Start();
            }
            Console.Write(
"Press any key to continue . . . ");
            Console.ReadKey(
true);
        }
        
static void Work()
        {
            
while(true)
            {
                semahoro.WaitOne();
                Console.WriteLine(
"11111");
                Thread.Sleep(
1000);
                semahoro.Release();
            }
        }
    }
}