线程优先级设置

3

我刚刚用三个线程(包括主线程)制作了一个倒计时应用程序。我将CountdownEven设置为较低的优先级,以便让countdownOdd先显示,但是在输出中没有发生任何事情。有人看到问题了吗?

//Main
public class CountdownApp 
{

    public static void main(String[] args) 
    {
    new CountdownApp().start();

    }
    public void start()
    {
        Thread count1 = new CountdownEven();
        Thread count2 = new CountdownOdd();
        count1.setPriority(Thread.MIN_PRIORITY);
        count2.setPriority(Thread.MAX_PRIORITY);
        count1.start();
        count2.start();
    }

}


public class CountdownEven extends Thread
{
    public void run()
    {
        for(int i = 10; i > 0; i-=2)
        {
            System.out.println(this.getName()+ " Count: " +i);
            Thread.yield();//This is to allow the other thread to run.
    }
    }


}

public class CountdownOdd extends Thread
{
    public void run()
    {
        for(int i = 9; i > 0; i-=2)
        {
            System.out.println(this.getName()+ " Count: " +i);
            Thread.yield();//This is to allow the other thread to run.
    }
    }

}

3
设置优先级并不能保证执行顺序,尤其是在如此短的时间内。 - Denys Séguret
我刚刚运行了你的代码,得到了输出:线程1 计数:9 / 线程1 计数:7 / 线程1 计数:5 等等。 - assylias
1
使用优先级并不是定义线程运行顺序的正确方式。 - assylias
@assylias 奇怪,我也运行了它,并得到了预期的输出(10、9、8、...)。但这可能只是运气。这绝对不是排序的正确方式。 - Guillaume Polet
编译和运行对我来说都很好。但是,由于使用线程优先级不适合预期的目的,输出可能不如预期。所以回答问题:“不,我看不到问题,因为对我来说没有问题。” - esej
1个回答

2
我尝试了你的代码,它确实产生了输出。
Thread-0 Count: 10
Thread-0 Count: 8
Thread-0 Count: 6
Thread-0 Count: 4
Thread-0 Count: 2
Thread-1 Count: 9
Thread-1 Count: 7
Thread-1 Count: 5
Thread-1 Count: 3
Thread-1 Count: 1

输出结果正常,那么你的问题是什么? 也许你只需要在eclipse中打开一个新的控制台窗口/选项卡,或者你有任何活动过滤器?

但是我个人认为,我不会使用Threadpriorities来实现这个目的,请参见 http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/Thread.html


1
即使您的操作系统不忽略提示,如果您有足够的空闲 CPU,每个想要运行的线程都会运行,无论其优先级如何。 - Peter Lawrey
2
我想补充一点,使用线程优先级 1)是特定于平台的 2)不能保证有效 3)在极端情况下可能导致某些线程永远不会被执行(饥饿)。 - assylias

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接