为什么线程不按优先级运行

时间:2013-12-02 12:46:58

标签: c# multithreading

我在这个程序中有一个问题我想根据优先级运行线程但是当我运行这个程序时输出是

say hello
say bye

但我想优先改变顺序请帮帮我。因为say bye的修道院很高

say bye
say hello
using System;
using System.Threading;

class Program
{
    public void Sayhello()
    {
        Console.WriteLine("say hello");
    }

    public void Saybye()
    {
        Console.WriteLine("say bye");
    }

    static void Main(string[] args)
    {
        Program ob = new Program();

        Thread  th = new Thread(new ThreadStart(ob.Sayhello));
        th.Priority = ThreadPriority.Lowest;
        th.Start();

        Thread th1 = new Thread(new ThreadStart(ob.Saybye));
        th1.Priority = ThreadPriority.Highest;
        th1.Start();

        Console.ReadLine();
    }
}

2 个答案:

答案 0 :(得分:2)

系统使用线程优先级来决定在准备运行的线程多于处理器时运行哪个线程。在这种情况下,优先级较高的线程首先运行。

在你的情况下,这似乎是合理的:

  1. 低优先级线程在高优先级线程准备运行之前已经启动,或者
  2. 您有足够的处理器,两个线程可以同时运行。
  3. 线程优先级不是可用于确保执行顺序的工具。您需要使用线程同步对象。

    通常,您很少设置线程的优先级。通常,最好让操作系统决定如何调度线程。

答案 1 :(得分:0)

在th之后开始th1可能会这样做:

th1.Start();
th.Start()

但是仍然无法保证,你需要阻止直到一个完成,这就引出了为什么要使用线程的问题?

Sayhello();
Saybye();

如果你必须在hello完成时发出信号,那么再见就可以继续:

private ManualResetEvent waitHandel;

public void Sayhello()
{
    Console.WriteLine("say hello");
    waitHandel.Set();
}

public void Saybye()
{
    waitHandel.WaitOne();
    Console.WriteLine("say bye");
}


static void Main(string[] args)
{
    waitHandel = new ManualResetEvent(false);

    Thread  th = new Thread(new ThreadStart(ob.Sayhello));
    th.Priority = ThreadPriority.Lowest;
    th.Start();

    Thread th1 = new Thread(new ThreadStart(ob.Saybye));
    th1.Priority = ThreadPriority.Highest;
    th1.Start();

    Console.ReadLine();
}
相关问题