using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading ; using System.Diagnostics ; namespace 多线程 { class Semaphore旗语锁定 { public static void Main() { //旗语锁与互斥锁很像,区别是,旗语可以定义同时由多个线程使用 //是一种计数的互斥锁 //例如,要访问物理的IO端口,且有三个端口可以用,只允许3个线程同时访问IO。 //那么第4个线程则要等前3个中的其中之一释放锁以后,才能抢到锁 int threadCount = 6 ; int semaphoreCount = 4 ; //初始数与最大请求数都为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 ) ; } } } } }