2016-04-18 9 views
-1

JavaチュートリアルのOracleから以下のコードを見ました。私はちょうどそれが中断された後にメインスレッドにスレッドを再結合する点は何ですか?スレッドが中断された後、スレッドをメインスレッドに再結合する点は何ですか?

if(((System.currentTimeMillis() - startTime) > patience) && t.isAlive()){ 
    threadMessage("tired of waiting"); 
    t.interrupt(); 
    t.join(); 

} 

文と、すべてがまったく同じに働いているように見える場合、私はからt.join()を削除しました。だから、なぜコードはそれがしたように書かれていたのですか?

public class SimpleThreads { 


    static void threadMessage(String message){ 
     String threadName = Thread.currentThread().getName(); 
     System.out.format("%s: %s%n", threadName, message); 
    } 

    private static class MessageLoop implements Runnable { 

     @Override 
     public void run(){ 
      String[] importantInfo = { "dog", "cat", "mice"}; 

      try { 
       for(int i = 0; i < importantInfo.length; i++){ 
        Thread.sleep(4000); 
        threadMessage(importantInfo[i]); 
       } 
      } catch (InterruptedException e){ 
       threadMessage("i wasn't done!"); 
      } 
     } 
    } 

    public static void main(String[] args) throws InterruptedException { 
     long patience = 10000; 

     threadMessage("starting MessageLoop thread"); 
     long startTime = System.currentTimeMillis(); 
     Thread t = new Thread(new MessageLoop()); 
     t.start(); 

     threadMessage("waiting for MessageLoop thread to finish"); 
     while(t.isAlive()){ 
      threadMessage("still waiting..."); 
      t.join(1000); 

      if(((System.currentTimeMillis() - startTime) > patience) && t.isAlive()){ 
       threadMessage("tired of waiting"); 
       t.interrupt(); 
       t.join(); 

      } 
     } 
     threadMessage("finally"); 
    } 


} 

答えて

2

あなたは

t.join(1000); 

呼び出すとJavaは、あなたはそれが1000ミリ秒以内に完了することを期待されている対応するスレッドに通知する努力をしません。そのスレッドがIOのブロッキングを行っているか、あなたのスレッドのようにスリープしている場合は、そのスレッドはそのまま処理を続けます。

このチュートリアルでは、よりクリーンなシャットダウンパターンを示しています。彼らは最初にinterruptsleepから目を覚ますスレッド(実行しているものなら)を終了し、最終的に終了します。その後、その終了を待つためにjoin()に電話します。

joinが省略されている可能性がありますが、スレッドの種類(目的)によってはアプリケーションが予期しない状態になっている可能性があります。


これを繰り返すことは、共同作業であることを繰り返すことが重要です。スレッドをきれいに終了させるには、適切な割り込みパターンを公開する必要があります。

関連する問題