个性化阅读
专注于IT技术分析

C#线程优先级

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

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
赞(0)
未经允许不得转载:srcmini » C#线程优先级

评论 抢沙发

评论前必须登录!