具有优先级设置的线程

时间:2012-04-30 14:53:55

标签: java multithreading thread-priority

我刚刚制作了一个包含主线程在内的三个线程的倒计时应用。我将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.
    }
    }

}

1 个答案:

答案 0 :(得分: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中打开一个新的控制台小部件/选项卡,或者你有任何有效的过滤器?

但是imho我不会为此目的使用Threadpriorities,请参阅 http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/Thread.html