線程池設置最多M線程執行N個任務

轉載地址:http://www.ithao123.cn/content-4805192.htmlhtml

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace 多線程池試驗
{
    class Program
    {
        public static void Main()
        {
            //新建ManualResetEvent對象而且初始化爲無信號狀態
            ManualResetEvent eventX = new ManualResetEvent(false);
            ThreadPool.SetMaxThreads(3, 3);
            thr t = new thr(15, eventX);
            for (int i = 0; i < 15; i++)
            {
                ThreadPool.QueueUserWorkItem(new WaitCallback(t.ThreadProc), i);
            }
            //等待事件的完成,即線程調用ManualResetEvent.Set()方法
            //eventX.WaitOne  阻止當前線程,直到當前 WaitHandle 收到信號爲止。 
            eventX.WaitOne(Timeout.Infinite, true);
            Console.WriteLine("斷點測試");
            Thread.Sleep(10000);
            Console.WriteLine("運行結束");
        }
 
        public class thr
        {
            public thr(int count,ManualResetEvent mre)
            {
                iMaxCount = count;
                eventX = mre;
            }
 
            public static int iCount = 0;
            public static int iMaxCount = 0;
            public ManualResetEvent eventX;
            public void ThreadProc(object i)
            {
                Console.WriteLine("Thread[" + i.ToString() + "]");
                Thread.Sleep(2000);
                //Interlocked.Increment()操做是一個原子操做,做用是:iCount++ 具體請看下面說明 
                //原子操做,就是不能被更高等級中斷搶奪優先的操做。你既然提這個問題,我就說深一點。
                //因爲操做系統大部分時間處於開中斷狀態,
                //因此,一個程序在執行的時候可能被優先級更高的線程中斷。
                //而有些操做是不能被中斷的,否則會出現沒法還原的後果,這時候,這些操做就須要原子操做。
                //就是不能被中斷的操做。
                Interlocked.Increment(ref iCount);
                if (iCount == iMaxCount)
                {
                    Console.WriteLine("發出結束信號!");
                    //將事件狀態設置爲終止狀態,容許一個或多個等待線程繼續。
                    eventX.Set();
                }
            }
        }
    }
}

  

 

轉載地址:http://www.ithao123.cn/content-4805192.html多線程

相關文章
相關標籤/搜索