2012-04-30 57 views
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

设置优先级将不能保证执行顺序,尤其是在这样短的时间。 –

+0

我刚刚运行你的代码,我得到一个输出:'线程1计数:9' /'线程1计数:7' /'线程1计数:5'等 – assylias

+1

使用优先级不是正确的方式来定义线程的运行顺序。 – assylias

回答

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中打开一个新的控制台widget/tab,或者你有任何活动的过滤器?

但恕我直言,我不会使用Threadpriorities为此,见 http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/Thread.html

+1

+1:即使您的操作系统不会忽略该提示,但如果每个想要运行的线程都有足够的空闲CPU,则无论优先级如何,都会运行。 –

+2

我会补充说,使用线程优先级1)是特定于平台2)不保证工作,并且3)可以在一些极端情况下导致某些线程永远不会执行(饥饿)。 – assylias