.NET多线程技术详解(4) 线程优先级

 

线程优先级从高到低分为:Highest AboveNormalNormalBelowNormalLowest5个等级。通过设置Thread类的ThreadPriority属性(可读写属性)来调整。

范例:

下面的代码示例说明了更改线程优先级的结果。创建两个线程,其中一个线程的优先级设置为 BelowNormal。两个线程在 while 循环中都增加一个变量,并运行一段设定的时间。

using System;

using System.Threading;

class Test

{

    static void Main()

    {

        PriorityTest priorityTest = new PriorityTest();

        ThreadStart startDelegate =

            new ThreadStart(priorityTest.ThreadMethod);

        Thread threadOne = new Thread(startDelegate);

        threadOne.Name = "ThreadOne";//通过设置线程的name加以区分。

        Thread threadTwo = new Thread(startDelegate);

        threadTwo.Name = "ThreadTwo";

 

        threadTwo.Priority = ThreadPriority.BelowNormal;

        threadOne.Start();

        threadTwo.Start();

 

        // Allow counting for 10 seconds.

        Thread.Sleep(10000);

        priorityTest.LoopSwitch = false;

        Console.ReadLine();

    }

}

 

class PriorityTest

{

    bool loopSwitch;

    public PriorityTest()

    {

        loopSwitch = true;

    }

 

    public bool LoopSwitch

    {

        set { loopSwitch = value; }

    }

 

    public void ThreadMethod()

    {

        long threadCount = 0;

 

        while (loopSwitch)

        {

            threadCount++;

        }

        Console.WriteLine("{0} with {1,11} priority " +

            "has a count = {2,13}", Thread.CurrentThread.Name,

            Thread.CurrentThread.Priority.ToString(),

            threadCount.ToString("N0"));

    }

}

运行结果:很明显,高优先级的线程拥有更多的运行机会。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值