C#中Thread的优先级不是决定每个线程被执行顺序。它决定了线程可以占用CPU的时间

Thread的优先级设置是自带的枚举类型"ThreadPriority"

 [ComVisible(true)]
public enum ThreadPriority
{
//
// 摘要:
// System.Threading.Thread 可以安排在具有任何其他优先级的线程之后。
Lowest = ,
//
// 摘要:
// System.Threading.Thread 可以安排在使用的线程之后 Normal 优先级之前 Lowest 优先级。
BelowNormal = ,
//
// 摘要:
// System.Threading.Thread 可以安排在使用的线程之后 AboveNormal 优先级之前 BelowNormal 优先级。 线程所具有的
// Normal 默认优先级。
Normal = ,
//
// 摘要:
// System.Threading.Thread 可以安排在使用的线程之后 Highest 优先级之前 Normal 优先级。
AboveNormal = ,
//
// 摘要:
// System.Threading.Thread 可以安排在具有任何其他优先级的线程之前。
Highest =
}

看下面两个线程的例子

class Program
{
static void Main(string[] args)
{
Thread thread1 = new Thread(PrintCount);
Thread thread2 = new Thread(PrintCount);
thread1.Priority = ThreadPriority.Highest;
thread2.Priority = ThreadPriority.Lowest;
thread1.Start();
thread2.Start();
Thread.Sleep();
thread1.Abort();
thread2.Abort();
Console.Read();
}
private static void PrintCount()
{
int flag = ;
while (true)
{
Console.WriteLine($"{Thread.CurrentThread.Name}priority{Thread.CurrentThread.Priority}count:{flag++ }");
}
}
}

我们运行了两个子线程,第一个线程设置为了最高级,第二个则是最低级,在两秒内,我们看看下面的结果

第一个设置为高级的线程在两秒内运行了912次,而设置为低级的则运行了645次

因为我们计算机性能都比较好了,基本都是几核的。接下来我们稍微修改下代码,我们将所有的线程都放知道我们系统的第一个CPU上运行

来看看运行状况。

class Program
{
static void Main(string[] args)
{
Thread thread1 = new Thread(PrintCount);
Thread thread2 = new Thread(PrintCount);
thread1.Priority = ThreadPriority.Highest;
thread2.Priority = ThreadPriority.Lowest;
thread1.Start();
thread2.Start();
Process.GetCurrentProcess().ProcessorAffinity = new IntPtr();//设置到第一个cup上运行
Thread.Sleep();
thread1.Abort();
thread2.Abort();
Console.Read();
}
private static void PrintCount()
{
int flag = ;
while (true)
{
Console.WriteLine($"{Thread.CurrentThread.Name}priority{Thread.CurrentThread.Priority}count:{flag++ }");
}
}

我们看看两秒内两个线程的运行情况

由此可见,低等级的次数更少了,这是由于只使用了一个CPU核心,所以它大多时间都是在处理高等级的线程,更少的时间处理低等级。这里可以看到差距更加的明显了。

最新文章

  1. 什么是Unicode letter
  2. 自定义Toast解决快速点击时重复弹出,排队无止尽
  3. JDBC向数据库中插入数据
  4. 二叉查找树的Java实现
  5. thinkphp 删除多条记录
  6. Collection集合List、Set
  7. X230上安装Yosemite/Win7-黑苹果之路
  8. ajax学习计划
  9. ajax全局函数运用
  10. 解决java.sql.SQLException: ORA-01789: query block has incorrect number of result columns
  11. hihocoder_1014: Trie树(Trie树模板题)
  12. MySQL字符串进行加减乘除的运算
  13. WPF常用TriggerAction用法 (一)
  14. HDU1075 字典树板子题
  15. scrapy基础 之 爬虫入门:先用urllib2来理解爬虫
  16. Python实现图像信息隐藏
  17. springCloud配置本地配中心SpringCloudConfig
  18. USG防火墙DHCP设置保留IP地址
  19. MDX Step by Step 读书笔记(七) - Performing Aggregation 聚合函数之 Sum, Aggregate, Avg
  20. 做了 3 年企业级 SaaS,我收获的 10 点心得(转)

热门文章

  1. 简单的物流项目实战,WPF的MVVM设计模式(五)
  2. 前端为什么要学习 Selenium
  3. 解决HTML乱码
  4. AVCaptureSession拍照,摄像,载图总结
  5. Mysql逻辑架构介绍
  6. Spring基础07——配置集合属性
  7. ubuntu下docker安装
  8. 1--面试总结-js深入理解,对象,原型链,构造函数,执行上下文堆栈,执行上下文,变量对象,活动对象,作用域链,闭包,This
  9. 详解Spring MVC 集成EHCache缓存_java - JAVA
  10. DI,依赖注入,给对象赋值 ,get,set,list,set,map,properties对象赋值