線程池Demo

來源:互聯網
上載者:User
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();         }    }}

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.