using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
namespace ConsoleApplication58
{
class MultiThreading
{
static void Main(string[] args)
{
MultiThreading mul = new MultiThreading();
Thread t1 = new Thread(new ThreadStart(mul.WriteX));
Thread t2 = new Thread(new ThreadStart(mul.WriteO));
t1.Priority = ThreadPriority.Lowest;
t2.Priority = ThreadPriority.Highest;
t1.Start();
t2.Start();
}
private void WriteX()
{
for (int i = 0; i < 300; i++)
{
Console.Write("X");
}
}
private void WriteO()
{
for (int i = 0; i < 300; i++)
{
Console.Write("O");
}
}
}
}当我执行上面的代码时,我期望X结束打印任务,因为我给了这个方法最低的优先级,但有时我在最后得到O。我的意思是,给予第二线程高优先级不能保证它能更快地完成吗?
发布于 2016-06-30 13:53:03
优先级设置对线程调度没有实际的保证。
例如,高优先级线程可能会阻塞IO或页面错误。然后,另一个线程可以执行。
这不是同步线程的好方法。
发布于 2017-04-20 15:38:45
CPU的300次操作是秒的一部分。我建议您将您的问题和应用作为一个统计实验来考虑。
重复你的实验多次,因为很少运行它们是不值得信赖的。发生这种情况是因为总体(迭代次数不够大)。我试着运行这个应用程序几次,但是通过3000次迭代,我允许编写45秒( this (True)和Thread.Sleep(45000))。优先级较高的任务先完成。
您的操作系统、CPU和PC配置确实很重要。
https://stackoverflow.com/questions/38125086
复制相似问题