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.
    }
    }

}
4

1 回答 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

于 2012-04-30T15:02:00.323 回答