C#教程:线程的优先权
来源:原创 作者:小人物 录入时间:2009-09-28
内容导读:
每个线程都具有分配给它的线程优先级。为在公共语言运行库中创建的线程最初分配的优先级为ThreadPriority.Normal。在运行库外创建的线程会保留它们在进入托管环境之前所具有的优先级
线程的优先权 每个线程都具有分配给它的线程优先级。为在公共语言运行库中创建的线程最初分配的优先级为ThreadPriority.Normal。在运行库外创建的线程会保留它们在进入托管环境之前所具有的优先级。用户可以使用Thread.Priority属性获取或设置任何线程的优先级。 线程是根据其优先级而调度执行的。即使线程正在运行库中执行,所有线程都是由操作系统分配处理器时间片的。用于确定线程执行顺序的调度算法的详细情况随每个操作系统的不同而不同。在某些操作系统下,具有最高优先级(相对于可执行线程而言)的线程经过调度后总是首先运行。如果具有相同优先级的多个线程都可用,则计划程序将遍历处于该优先级的线程,并为每个线程提供一个固定的时间片来执行。如果在给定的优先级上不再有可运行的线程,则计划程序将移到下一个较低的优先级并在该优先级上调度线程以执行。如果具有较高优先级的线程可以运行,则具有较低优先级的线程将被抢先,并允许具有较高优先级的线程再次执行。除此之外,当应用程序的用户界面在前台和后台之间移动时,操作系统还可以动态调整线程优先级。其他操作系统可以选择使用不同的调度算法。 可以为线程分配以下任何一个优先级值,如下所示。 Highest AboveNormal Normal BelowNormal Lowest 示例 线程的优先级 下面的示例展示了如何使用优先级。 using
System; using System.Threading; class Test { static void
Main() { PriorityTest priorityTest = new PriorityTest(); Thread
threadOne = new Thread(new
ThreadStart(priorityTest.ThreadMethod)); threadOne.Name = "线程1"; Thread
threadTwo = new Thread(new
ThreadStart(priorityTest.ThreadMethod)); threadTwo.Name =
"线程2"; threadTwo.Priority =
ThreadPriority.BelowNormal; threadOne.Start(); threadTwo.Start(); //
线程休眠20s Thread.Sleep(20000); priorityTest.LoopSwitch =
False; } } 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")); } } 完整程序代码如下: ★
★★★★Program.cs主程序文件完整程序代码★★★★★ using System; using
System.Collections.Generic; using System.Text; using
System.Threading; namespace _8_03 { class Test { static void
Main(string[] args) { PriorityTest priorityTest = new
PriorityTest(); Thread threadOne = new Thread(new
ThreadStart(priorityTest.ThreadMethod)); threadOne.Name = "线程1"; Thread
threadTwo = new Thread(new
ThreadStart(priorityTest.ThreadMethod)); threadTwo.Name =
"线程2"; threadTwo.Priority =
ThreadPriority.BelowNormal; threadOne.Start(); threadTwo.Start(); //
线程休眠20秒 Thread.Sleep(20000); priorityTest.LoopSwitch =
false; } } class PriorityTest { bool loopSwitch; public
PriorityTest() { loopSwitch = true; } public bool
LoopSwitch { set { loopSwitch = value; } } public void
ThreadMethod() { long threadCount = 0; while (loopSwitch)
Tags:网络编程
C#教程
责任编辑:admin
C#教程:线程的优先权(2)
来源:原创 作者:小人物 录入时间:2009-09-28
内容导读: { threadCount++; }
Console.WriteLine({0} with {1,11} priority + has a count = {2,13},
Thread.CurrentThread.Name, Thread.CurrentThread.Priority.ToString(),
threadCount.ToString(N0)); } } }
{ threadCount++; } Console.WriteLine("{0} with
{1,11} priority " + "has a count = {2,13}",
Thread.CurrentThread.Name, Thread.CurrentThread.Priority.ToString(), threadCount.ToString("N0")); } } }
|