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