實現思路:線程執行后進行阻塞,判斷當前標記是否達到設置的並發數,如果未達到上限,執行隊列中將繼續增加線程;如已達到其余線程排隊等候。
實例代碼:
注:其中用到Mutex與Interlocked兩個與線程相關的類,需要加上 using System.Threading; 引用Threading命名空間。
public class MutexTest { private static int poolFlag = 0; //聲明標記 private const int amountThread = 10;//線程總量 private const int maxThread = 3;//可執行線程最大數量 private static Mutex muxConsole = new Mutex(); public static void Main() { for (int i = 0; i < amountThread; i++) { // 創建指定數量的線程,線程調用Run函數 Thread trd = new Thread(new ThreadStart(Run)); trd.Name = "線程" + i; trd.Start(); } } public static void Run() { muxConsole.WaitOne(); //阻塞隊列 Interlocked.Increment(ref poolFlag); //標記+1 if (poolFlag < maxThread) //判斷是否達到線程上限 muxConsole.ReleaseMutex(); //釋放隊列鎖,加入執行線程 Console.WriteLine("{0} 正在運行......\n", Thread.CurrentThread.Name); Thread.Sleep(3000); //模擬執行,暫停3秒鍾 Console.WriteLine("{0} 已經中止......\n", Thread.CurrentThread.Name); Interlocked.Decrement(ref poolFlag); //標記-1 try { muxConsole.ReleaseMutex(); //釋放阻塞 } catch { } } }