2012-04-30 25 views
3

私はちょうどメインスレッドを含む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

私はあなたのコードを実行しました。出力は 'Thread-1 Count:9' /' Thread-1 Count:7'/'Thread-1 Count: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で新しいコンソールウィジェット/タブを開くか、アクティブなフィルタが必要なのでしょうか?

しかし、私は文句を言わない、この目的のためにThreadprioritiesを使用私見、特にこのような短い期間に、実行順序を保証するものではありません優先順位を設定する http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/Thread.html

+1

+1:あなたのOSがヒントを無視しなくても、実行するスレッドごとに十分な空きCPUがある場合、優先順位に関係なく実行されます。 –

+2

スレッドの優先順位を使用して、1)プラットフォーム固有2)動作保証されていない、3)いくつかの極端な場合に実行されないスレッド(飢え)につながる可能性があります。 – assylias

関連する問題