//初始数与最大请求数都为4
Semaphore semaphore = new Semaphore( semaphoreCount , semaphoreCount );
Thread[] threads = new Thread[ threadCount ] ;
for( int i = 0 ; i < threads.Length ; i ++ )
{
threads[i] = new Thread( ThreadMain ) ;
threads[i].Start( semaphore ) ;
}
for( int i = 0 ; i < threadCount ; i ++ )
{
//保证所有线程在主线程之前完成
threads[ i ].Join() ;
}
Console.WriteLine( "执行完毕" ) ;
Console.ReadLine() ;
}
public static void ThreadMain( object o )
{
Semaphore semaphore = o as Semaphore ;
Trace.Assert( semaphore != null , "参数类型不对" ) ;
bool isCompleted = false ;
while( !isCompleted )
{
if( semaphore.WaitOne( 600 , false ) )
{
try
{
Console.WriteLine( "线程:{0} 拿到了锁" , Thread.CurrentThread.ManagedThreadId ) ;
// 拿到后睡上2秒
Thread.Sleep( 2000 ) ;
}
finally
{
semaphore.Release() ;
Console.WriteLine( "---线程 {0} 放掉了锁" , Thread.CurrentThread.ManagedThreadId ) ;
isCompleted = true ;
}
}
else
{
Console.WriteLine( "!!!线程{0}等待超时 " , Thread.CurrentThread.ManagedThreadId ) ;
}
}
}
}
}