📜  C#线程示例:ThreadPriority

📅  最后修改于: 2020-10-31 14:11:21             🧑  作者: Mango

C#线程示例:ThreadPriority

让我们看一个更改线程优先级的示例。高优先级线程可以首先执行。但这不能保证,因为线程高度依赖于系统。它增加了高优先级线程在低优先级线程之前执行的机会。

using System;
using System.Threading;
public class MyThread
{
    public void Thread1()
    {
        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 = "Player1";
        t2.Name = "Player2";
        t3.Name = "Player3";
        t3.Priority = ThreadPriority.Highest;
        t2.Priority = ThreadPriority.Normal;
        t1.Priority = ThreadPriority.Lowest;

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

输出:

由于线程高度依赖于系统,因此输出是不可预测的。它可以遵循任何抢占式或非抢占式算法。

Player1 is running
Player3 is running
Player2 is running