http://book.51cto.com/art/200806/77425.htm
class Test
{
static void Main()
{
PriorityTest work = new PriorityTest();
//创建线程并设置线程执行方法
Thread threadOne = new Thread(new ThreadStart(work.ThreadMethod));
threadOne.Name = "线程1";
Thread threadTwo = new Thread(new ThreadStart(work.ThreadMethod));
threadTwo.Name = "线程2";
//设置优先级
threadTwo.Priority = ThreadPriority.BelowNormal;
threadOne.Start(); threadTwo.Start();
//让两个线程都计算2秒钟
Thread.Sleep(2000);
//停止计算
work.LoopSwitch = false;
}
}
class PriorityTest
{
//用来控制While循环,为false就退出While循环
bool loopSwitch;
//构造方法
public PriorityTest()
{
loopSwitch = true;
}
public bool LoopSwitch
{
set { loopSwitch = value; }
}
//线程的方法,执行数数操作
public void ThreadMethod()
{
long threadCount = 0;
//进行加法操作
while (loopSwitch) { threadCount++; }
//显示结果
Console.WriteLine("{0},优先级:{1}" + "数到:{2}", Thread.CurrentThread.Name, Thread.CurrentThread.Priority.ToString(), threadCount.ToString());
}
}
本文提供了一个使用C#编写的简单示例,演示了如何通过设置不同优先级来观察线程的行为变化。通过创建两个执行相同任务但优先级不同的线程,可以直观地看到优先级对线程执行的影响。
4757

被折叠的 条评论
为什么被折叠?



