自己写了一个测试小程序,但是设置的优先级并不能先显示,请指点:
 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());
        }
    }

解决方案 »

  1.   

    试试:
    public static void Main() 

       StartTheEngine() ;

      

  2.   

    有什么问题吗?你的代码我编译成功,执行也没大问题啊?结果如下:
    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总是先执行的话,应该使用同步进行控制,绝对不应依赖优先级。
    而且优先级只是让线程取得更多的时间片而已,也不是说优先启动这个线程(当然,在同时建立了线程上下文之后,它的确最有可能先启动)。
      

  3.   

    线程优先级只有在CPU使用单核100%,双核50%,而且线程运行时间长。才有效
      

  4.   

    运行了下你的程序 确实如你所说 具体原因我也不知道 不过感觉4楼原因不正确 要是真根据cpu的使用率判断 那线程优先级好像作用就不大了
      

  5.   

    原因是你的委托函数写的太简单了,虽然你给T3指定了最高优先级别.
    但在以下的运行中,T1,T2并不会因为T3指定了最高优先级别而不运行,等到T3启动时,T1,T2早已经运行完了.所以你看不到什么效果.
    T3启动时,T1,T2会停止运行.等待T3运行完后,再运行.
      

  6.   

    每个线程都具有分配给它的线程优先级。为在公共语言运行库中创建的线程最初分配的优先级为 ThreadPriority.Normal。在运行库外创建的线程会保留它们在进入托管环境之前所具有的优先级。您可以使用 Thread.Priority 属性获取或设置任何线程的优先级。线程是根据其优先级而调度执行的。即使线程正在运行库中执行,所有线程都是由操作系统分配处理器时间片的。用于确定线程执行顺序的调度算法的详细情况随每个操作系统的不同而不同。在某些操作系统下,具有最高优先级(相对于可执行线程而言)的线程经过调度后总是首先运行。如果具有相同优先级的多个线程都可用,则计划程序将遍历处于该优先级的线程,并为每个线程提供一个固定的时间片来执行。只要具有较高优先级的线程可以运行,具有较低优先级的线程就不会执行。如果在给定的优先级上不再有可运行的线程,则计划程序将移到下一个较低的优先级并在该优先级上调度线程以执行。如果具有较高优先级的线程可以运行,则具有较低优先级的线程将被抢先,并允许具有较高优先级的线程再次执行。除此之外,当应用程序的用户界面在前台和后台之间移动时,操作系统还可以动态调整线程优先级。其他操作系统可以选择使用不同的调度算法。
    CUP不忙的情况下,你创建的线程太简单了,在给定的时间片内很快就能执行完毕,所以不会被优先级高的线程抢先。