多線程教程(二):線程池(ThreadPool)


一、ThreadPool

ThreadPool是.Net Framework 2.0版本中出現的。

ThreadPool出現的背景:Thread功能繁多,而且對線程數量沒有管控,對於線程的開辟和銷毀要消耗大量的資源。每次new一個THread都要重新開辟內存。

如果某個線程的創建和銷毀的代價比較高,同時這個對象還可以反復使用的,就需要一個池子(容器),保存多個這樣的對象,需要用的時候從池子里面獲取,用完之后不用銷毀,在放到池子里面。這樣不但能節省內存資源,提高性能,而且還能管控線程的總數量,防止濫用。這時就需要使用ThreadPool了。

我們來看看ThreadPool中常用的一些方法。

1、QueueUserWorkItem()

QueueUserWorkItem()方法用來啟動一個多線程。我們先看看方法的定義:

QueueUserWorkItem()方法有一個WaitCallback類型的參數,在看看WaitCallback的定義:

可以看到WaitCallback就是有一個object類型參數的委托,所以ThreadPool啟動多線程使用下面的代碼:

using System;
using System.Threading;

namespace ThreadPoolDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine($"start ThreadId: {Thread.CurrentThread.ManagedThreadId.ToString("00")}");
            // ThreadPoll啟動多線程
            ThreadPool.QueueUserWorkItem(p => DoSomethingLong("啟動多線程"));

            Console.WriteLine($"end ThreadId: {Thread.CurrentThread.ManagedThreadId.ToString("00")}");
            Console.ReadKey();
        }

        static void DoSomethingLong(string para)
        {
            Console.WriteLine($"{para}  ThreadId: {Thread.CurrentThread.ManagedThreadId.ToString("00")}");
        }
    }
}

運行結果:

2、GetMaxThreads()

GetMaxThreads()用來獲取線程池中最多可以有多少個輔助線程和最多有多少個異步線程。

1 ThreadPool.GetMaxThreads(out int workerThreads, out int completionPortThreads);
2 Console.WriteLine($"GetMaxThreads workerThreads={workerThreads} completionPortThreads={completionPortThreads}");

 程序運行結果:

3、GetMinThreads()

GetMinThreads()用來獲取線程池中最少可以有多少個輔助線程和最少有多少個異步線程。

ThreadPool.GetMinThreads(out int minworkerThreads, out int mincompletionPortThreads);
Console.WriteLine($"GetMinThreads workerThreads={minworkerThreads} completionPortThreads={mincompletionPortThreads}");

程序運行結果:

 

4、SetMaxThreads()和SetMinThreads()

SetMaxThreads()和SetMinThreads()分別用來設置線程池中最多線程數和最少線程數。

using System;
using System.Threading;

namespace ThreadPoolDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine($"start ThreadId: {Thread.CurrentThread.ManagedThreadId.ToString("00")}");
            // ThreadPoll啟動多線程
            ThreadPool.QueueUserWorkItem(p => DoSomethingLong("啟動多線程"));

            // 獲取最大線程
            ThreadPool.GetMaxThreads(out int workerThreads, out int completionPortThreads);
            Console.WriteLine($"GetMaxThreads workerThreads={workerThreads} completionPortThreads={completionPortThreads}");

            // 獲取最小線程
            ThreadPool.GetMinThreads(out int minworkerThreads, out int mincompletionPortThreads);
            Console.WriteLine($"GetMinThreads workerThreads={minworkerThreads} completionPortThreads={mincompletionPortThreads}");

            // 設置線程池線程
            SetThreadPool();
            // 輸出設置后的線程池線程個數
            Console.WriteLine("輸出修改后的最多線程數和最少線程數");
            ThreadPool.GetMaxThreads(out int maxworkerThreads, out int maxcompletionPortThreads);
            Console.WriteLine($"GetMaxThreads workerThreads={maxworkerThreads} completionPortThreads={maxcompletionPortThreads}");
            ThreadPool.GetMinThreads(out int workerEditThreads, out int completionPortEditThreads);
            Console.WriteLine($"GetMinThreads workerThreads={workerEditThreads} completionPortThreads={completionPortEditThreads}");
            Console.WriteLine($"end ThreadId: {Thread.CurrentThread.ManagedThreadId.ToString("00")}");
            Console.ReadKey();
        }

        static void DoSomethingLong(string para)
        {
            Console.WriteLine($"{para}  ThreadId: {Thread.CurrentThread.ManagedThreadId.ToString("00")}");
        }

        /// <summary>
        /// 設置線程池線程個數
        /// </summary>
        static void SetThreadPool()
        {

            Console.WriteLine("************設置最多線程數和最少線程數****************");
            // 設置最大線程
            ThreadPool.SetMaxThreads(16, 16);
            // 設置最小線程
            ThreadPool.SetMinThreads(8, 8);

        }
    }
}

程序運行結果:

二、線程等待

先來看下面一個小例子:

ThreadPool.QueueUserWorkItem(p => DoSomethingLong("啟動多線程"));
Console.WriteLine("等着QueueUserWorkItem完成后才執行");

 我們想讓異步多線程執行完以后再輸出“等着QueueUserWorkItem完成后才執行” 這句話,上面的代碼運行效果如下:

從截圖中可以看出,效果並不是我們想要的,Thread中提供了暫停、恢復等API,但是ThreadPool中沒有這些API,在ThreadPool中要實現線程等待,需要使用到ManualResetEvent類。

ManualResetEvent類的定義如下:

ManualResetEvent需要一個bool類型的參數來表示暫停和停止。上面的代碼修改如下:

// 參數設置為false
ManualResetEvent manualResetEvent = new ManualResetEvent(false);
ThreadPool.QueueUserWorkItem(p => 
{
      DoSomethingLong("啟動多線程");
      // 設置為true
      manualResetEvent.Set();
});
// 
manualResetEvent.WaitOne();
Console.WriteLine("等着QueueUserWorkItem完成后才執行");

 結果:

ManualResetEvent類的參數值執行順序如下:

(1)、false--WaitOne等待--Set--true--WaitOne直接過去
(2)、true--WaitOne直接過去--ReSet--false--WaitOne等待

注意:一般情況下,不要阻塞線程池中的線程,因為這樣會導致一些無法預見的錯誤。來看下面的一個例子:

static void SetWait()
{
            // 設置最大線程
            ThreadPool.SetMaxThreads(16, 16);
            // 設置最小線程
            ThreadPool.SetMinThreads(8, 8);
            ManualResetEvent manualResetEvent = new ManualResetEvent(false);
            for (int i = 0; i < 20; i++)
            {
                int k = i;
                ThreadPool.QueueUserWorkItem(p =>
                {
                    Console.WriteLine(k);
                    if (k < 18)
                    {
                        manualResetEvent.WaitOne();
                    }
                    else
                    {
                        // 設為true
                        manualResetEvent.Set();
                    }
                });
            }
            if (manualResetEvent.WaitOne())
            {
                Console.WriteLine("沒有死鎖、、、");
            }
            else
            {
                Console.WriteLine("發生死鎖、、、");
            }
}

啟動20個線程,如果k小於18就阻塞當前的線程,結果:

從截圖中看出,只執行了16個線程,后面的線程沒有執行,這是為什么呢?因為我們在上面設置了線程池中最多可以有16個線程,當16個線程都阻塞的時候,會造成死鎖,所以后面的線程不會再執行了。

三、線程重用

ThreadPool可以很好的實現線程的重用,這樣就可以減少內存的消耗,看下面的代碼:

/// <summary>
/// 測試ThreadPool線程重用
/// </summary>
static void ThreadPoolTest()
{
            // 線程重用
            ThreadPool.QueueUserWorkItem(t =>DoSomethingLong("ThreadPool"));
            ThreadPool.QueueUserWorkItem(t =>DoSomethingLong("ThreadPool"));
            ThreadPool.QueueUserWorkItem(t =>DoSomethingLong("ThreadPool"));
            ThreadPool.QueueUserWorkItem(t =>DoSomethingLong("ThreadPool"));
            ThreadPool.QueueUserWorkItem(t =>DoSomethingLong("ThreadPool"));
            Thread.Sleep(10 * 1000);
            Console.WriteLine("前面的計算都完成了。。。。。。。。");
            ThreadPool.QueueUserWorkItem(t =>DoSomethingLong("ThreadPool"));
            ThreadPool.QueueUserWorkItem(t =>DoSomethingLong("ThreadPool"));
            ThreadPool.QueueUserWorkItem(t =>DoSomethingLong("ThreadPool"));
            ThreadPool.QueueUserWorkItem(t =>DoSomethingLong("ThreadPool"));
            ThreadPool.QueueUserWorkItem(t =>DoSomethingLong("ThreadPool"));
}

然后在Main方法里面調用該方法,輸出結果如下圖所示:

我們在代碼里面總共創建了10個線程,而結果里面只有4個線程ID,這就說明ThreadPool可以實現線程的重用。下面我們在看看Thread是否可以實現線程的重用,代碼如下:

/// <summary>
/// 測試Thread線程重用
/// </summary>
static void ThreadTest()
{
            for (int i = 0; i < 5; i++)
            {
                new Thread(() => DoSomethingLong("Threads")).Start();
            }
            Thread.Sleep(10 * 1000);
            Console.WriteLine("前面的計算都完成了。。。。。。。。");
            for (int i = 0; i < 5; i++)
            {
                new Thread(() => DoSomethingLong("btnThreads")).Start();
            }
}

 然后在Main方法里面調用,輸入結果如下圖所示:

我們同樣在代碼里面創建了10個線程,結果輸出了10個線程的ID,這就說明Thread不能實現線程的重用。同樣也說明THread的效率沒有ThreadPool高。

程序完整代碼:

using System;
using System.Threading;

namespace ThreadPoolDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine($"start ThreadId: {Thread.CurrentThread.ManagedThreadId.ToString("00")}");
            //// ThreadPoll啟動多線程
            //ThreadPool.QueueUserWorkItem(p => DoSomethingLong("啟動多線程"));

            //// 獲取最大線程
            //ThreadPool.GetMaxThreads(out int workerThreads, out int completionPortThreads);
            //Console.WriteLine($"GetMaxThreads workerThreads={workerThreads} completionPortThreads={completionPortThreads}");

            //// 獲取最小線程
            //ThreadPool.GetMinThreads(out int minworkerThreads, out int mincompletionPortThreads);
            //Console.WriteLine($"GetMinThreads workerThreads={minworkerThreads} completionPortThreads={mincompletionPortThreads}");

            //// 設置線程池線程
            //SetThreadPool();
            //// 輸出設置后的線程池線程個數
            //Console.WriteLine("輸出修改后的最多線程數和最少線程數");
            //ThreadPool.GetMaxThreads(out int maxworkerThreads, out int maxcompletionPortThreads);
            //Console.WriteLine($"GetMaxThreads workerThreads={maxworkerThreads} completionPortThreads={maxcompletionPortThreads}");
            //ThreadPool.GetMinThreads(out int workerEditThreads, out int completionPortEditThreads);
            //Console.WriteLine($"GetMinThreads workerThreads={workerEditThreads} completionPortThreads={completionPortEditThreads}");
            //Console.WriteLine($"end ThreadId: {Thread.CurrentThread.ManagedThreadId.ToString("00")}");

            //// 參數設置為false
            //ManualResetEvent manualResetEvent = new ManualResetEvent(false);
            //ThreadPool.QueueUserWorkItem(p => 
            //{
            //    DoSomethingLong("啟動多線程");
            //    // 設置為true
            //    manualResetEvent.Set();
            //});
            //// 
            //manualResetEvent.WaitOne();
            //Console.WriteLine("等着QueueUserWorkItem完成后才執行");

            // SetWait();

            // ThreadPool實現線程的重用
            // ThreadPoolTest();

            // Thread
            ThreadTest();
            Console.WriteLine($"end ThreadId: {Thread.CurrentThread.ManagedThreadId.ToString("00")}");
            Console.ReadKey();
        }

        static void DoSomethingLong(string para)
        {
            Console.WriteLine($"{para}  ThreadId: {Thread.CurrentThread.ManagedThreadId.ToString("00")}");
        }

        /// <summary>
        /// 設置線程池線程個數
        /// </summary>
        static void SetThreadPool()
        {

            Console.WriteLine("************設置最多線程數和最少線程數****************");
            // 設置最大線程
            ThreadPool.SetMaxThreads(16, 16);
            // 設置最小線程
            ThreadPool.SetMinThreads(8, 8);

        }

        static void SetWait()
        {
            // 設置最大線程
            ThreadPool.SetMaxThreads(16, 16);
            // 設置最小線程
            ThreadPool.SetMinThreads(8, 8);
            ManualResetEvent manualResetEvent = new ManualResetEvent(false);
            for (int i = 0; i < 20; i++)
            {
                int k = i;
                ThreadPool.QueueUserWorkItem(p =>
                {
                    Console.WriteLine(k);
                    if (k < 18)
                    {
                        manualResetEvent.WaitOne();
                    }
                    else
                    {
                        // 設為true
                        manualResetEvent.Set();
                    }
                });
            }
            if (manualResetEvent.WaitOne())
            {
                Console.WriteLine("沒有死鎖、、、");
            }
            else
            {
                Console.WriteLine("發生死鎖、、、");
            }
        }

        /// <summary>
        /// 測試ThreadPool線程重用
        /// </summary>
        static void ThreadPoolTest()
        {
            // 線程重用
            ThreadPool.QueueUserWorkItem(t => DoSomethingLong("ThreadPool"));
            ThreadPool.QueueUserWorkItem(t => DoSomethingLong("ThreadPool"));
            ThreadPool.QueueUserWorkItem(t => DoSomethingLong("ThreadPool"));
            ThreadPool.QueueUserWorkItem(t => DoSomethingLong("ThreadPool"));
            ThreadPool.QueueUserWorkItem(t => DoSomethingLong("ThreadPool"));
            Thread.Sleep(10 * 1000);
            Console.WriteLine("前面的計算都完成了。。。。。。。。");
            ThreadPool.QueueUserWorkItem(t => DoSomethingLong("ThreadPool"));
            ThreadPool.QueueUserWorkItem(t => DoSomethingLong("ThreadPool"));
            ThreadPool.QueueUserWorkItem(t => DoSomethingLong("ThreadPool"));
            ThreadPool.QueueUserWorkItem(t => DoSomethingLong("ThreadPool"));
            ThreadPool.QueueUserWorkItem(t => DoSomethingLong("ThreadPool"));
        }

        /// <summary>
        /// 測試Thread線程重用
        /// </summary>
        static void ThreadTest()
        {
            for (int i = 0; i < 5; i++)
            {
                new Thread(() => DoSomethingLong("Threads")).Start();
            }
            Thread.Sleep(10 * 1000);
            Console.WriteLine("前面的計算都完成了。。。。。。。。");
            for (int i = 0; i < 5; i++)
            {
                new Thread(() => DoSomethingLong("btnThreads")).Start();
            }
        }
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM