C# Thread2——线程优先级
2024-10-07 10:26:41
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核心,所以它大多时间都是在处理高等级的线程,更少的时间处理低等级。这里可以看到差距更加的明显了。
最新文章
- 什么是Unicode letter
- 自定义Toast解决快速点击时重复弹出,排队无止尽
- JDBC向数据库中插入数据
- 二叉查找树的Java实现
- thinkphp 删除多条记录
- Collection集合List、Set
- X230上安装Yosemite/Win7-黑苹果之路
- ajax学习计划
- ajax全局函数运用
- 解决java.sql.SQLException: ORA-01789: query block has incorrect number of result columns
- hihocoder_1014: Trie树(Trie树模板题)
- MySQL字符串进行加减乘除的运算
- WPF常用TriggerAction用法 (一)
- HDU1075 字典树板子题
- scrapy基础 之 爬虫入门:先用urllib2来理解爬虫
- Python实现图像信息隐藏
- springCloud配置本地配中心SpringCloudConfig
- USG防火墙DHCP设置保留IP地址
- MDX Step by Step 读书笔记(七) - Performing Aggregation 聚合函数之 Sum, Aggregate, Avg
- 做了 3 年企业级 SaaS,我收获的 10 点心得(转)
热门文章
- 简单的物流项目实战,WPF的MVVM设计模式(五)
- 前端为什么要学习 Selenium
- 解决HTML乱码
- AVCaptureSession拍照,摄像,载图总结
- Mysql逻辑架构介绍
- Spring基础07——配置集合属性
- ubuntu下docker安装
- 1--面试总结-js深入理解,对象,原型链,构造函数,执行上下文堆栈,执行上下文,变量对象,活动对象,作用域链,闭包,This
- 详解Spring MVC 集成EHCache缓存_java - JAVA
- DI,依赖注入,给对象赋值 ,get,set,list,set,map,properties对象赋值