線程池Demo

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace ConsoleApplication2
{
    class Program
    {
        private static int poolFlag = 0;//標記
        private const int amountThread = 10;//線程總量
        private const int maxThread = 3;//可執行線程最大數量
        private static Mutex muxConsole = new Mutex();

        static void Main(string[] args)
        {
            for (int i = 0; i < amountThread; i++)
            {
                // 創建指定數量的線程
                // 是線程調用Run方法
                // 啓動線程
                Thread trd = new Thread(new ThreadStart(Run));
                trd.Name = "線程" + i;
                trd.Start();
            }
        }

        public static void Run()
        {
            bool releasedFlag = false;
            muxConsole.WaitOne(); //阻塞隊列
            Interlocked.Increment(ref poolFlag);//標記+1
            if (poolFlag != maxThread) //判斷是否等於上限
            {
                muxConsole.ReleaseMutex(); //如果此線程達不到可執行線程上限,則繼續開通,讓後面的線程進來
                releasedFlag = true;
            }
            Console.WriteLine("{0} 正在運行...... ", Thread.CurrentThread.Name);
            Thread.Sleep(5000); //模擬執行
            Console.WriteLine("{0} 已經中止...... ", Thread.CurrentThread.Name);
            //標記-1
            Interlocked.Decrement(ref poolFlag);
            if (!releasedFlag) muxConsole.ReleaseMutex(); 
        }
    }
}

 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章