C#線程示例:優先級

我們來看下面的一個例子,演示如何改變線程的優先級。高優先級線程優先執行。但是不能完全保證,因爲線程是高度依賴系統的。它只提高了優先級較高的線程在低優先級線程之前執行的機會。

using System;
using System.Threading;
public class MyThread
{
    public void Thread1()
    {
        for(int i=0; i<3; i++)
        {
            Thread t = Thread.CurrentThread;
            Console.WriteLine(t.Name + " is running");
        }


    }
}
public class ThreadExample
{
    public static void Main()
    {
        MyThread mt = new MyThread();
        Thread t1 = new Thread(new ThreadStart(mt.Thread1));
        Thread t2 = new Thread(new ThreadStart(mt.Thread1));
        Thread t3 = new Thread(new ThreadStart(mt.Thread1));
        t1.Name = "Highest-Thread ";
        t2.Name = "Normal-Thread ";
        t3.Name = "Lowest-Thread ";
        t1.Priority = ThreadPriority.Highest;
        t2.Priority = ThreadPriority.Normal;
        t3.Priority = ThreadPriority.Lowest;

        t1.Start();
        t2.Start();
        t3.Start();
    }
}

輸出是不可預測的,因爲線程系統依賴性高。它可以遵循任何算法搶先或非搶佔式來執行。

執行上面示例代碼,得到以下結果 -

Highest-Thread  is running
Normal-Thread  is running
Normal-Thread  is running
Normal-Thread  is running
Lowest-Thread  is running
Lowest-Thread  is running
Lowest-Thread  is running
Highest-Thread  is running
Highest-Thread  is running