自己写了一个测试小程序,但是设置的优先级并不能先显示,请指点:
public class Car
{ private static void ChecktheEngine()
{
Console.WriteLine("check the engine!");
}
private static void ChecktheBattery()
{
Console.WriteLine("check the battery!");
}
private static void ChecktheFuel()
{
Console.WriteLine("check the fuel!");
}
public void StartTheEngine()
{
Console.WriteLine("start the engine!");
Thread t1 = new Thread(new ThreadStart(ChecktheEngine));
Thread t2 = new Thread(new ThreadStart(ChecktheBattery));
Thread t3 = new Thread(new ThreadStart(ChecktheFuel));
t3.Priority = System.Threading.ThreadPriority.Highest;//此处设置的最高优先级,为什么不能实现呢?
t1.Start();
t2.Start();
t3.Start();
Console.ReadLine();
}
public static void Main()
{
Car car = new Car();
Thread ct = new Thread(new ThreadStart(car.StartTheEngine));
ct.Start();
Console.WriteLine("the main finished!");
Console.WriteLine("the thread ct state:" + ct.ThreadState.ToString());
Console.WriteLine("the thread ct culture:" + ct.CurrentCulture.ToString());
}
}
public class Car
{ private static void ChecktheEngine()
{
Console.WriteLine("check the engine!");
}
private static void ChecktheBattery()
{
Console.WriteLine("check the battery!");
}
private static void ChecktheFuel()
{
Console.WriteLine("check the fuel!");
}
public void StartTheEngine()
{
Console.WriteLine("start the engine!");
Thread t1 = new Thread(new ThreadStart(ChecktheEngine));
Thread t2 = new Thread(new ThreadStart(ChecktheBattery));
Thread t3 = new Thread(new ThreadStart(ChecktheFuel));
t3.Priority = System.Threading.ThreadPriority.Highest;//此处设置的最高优先级,为什么不能实现呢?
t1.Start();
t2.Start();
t3.Start();
Console.ReadLine();
}
public static void Main()
{
Car car = new Car();
Thread ct = new Thread(new ThreadStart(car.StartTheEngine));
ct.Start();
Console.WriteLine("the main finished!");
Console.WriteLine("the thread ct state:" + ct.ThreadState.ToString());
Console.WriteLine("the thread ct culture:" + ct.CurrentCulture.ToString());
}
}
public static void Main()
{
StartTheEngine() ;
}
the main finished!
start the engine!
the thread ct state:WaitSleepJoin
the thread ct culture:zh-CN
check the engine!
check the fuel!
check the battery!
如果你要求check the fuel总是先执行的话,应该使用同步进行控制,绝对不应依赖优先级。
而且优先级只是让线程取得更多的时间片而已,也不是说优先启动这个线程(当然,在同时建立了线程上下文之后,它的确最有可能先启动)。
但在以下的运行中,T1,T2并不会因为T3指定了最高优先级别而不运行,等到T3启动时,T1,T2早已经运行完了.所以你看不到什么效果.
T3启动时,T1,T2会停止运行.等待T3运行完后,再运行.
CUP不忙的情况下,你创建的线程太简单了,在给定的时间片内很快就能执行完毕,所以不会被优先级高的线程抢先。