2016-09-23 7 views
-1

2つのクラスを作成しました.CheckTimerは、0.3秒が経過したときに割り込みするために使用されます。thread1私はthread.interrupted()CheckTimer.run()で実行されたが、メイン関数のInterruptedExceptionは投げられなかったことに気付きました。thread1は何のヒントもなく実行を続けました、なぜですか? をthread1.interrupted()は止めますか?スレッドが中断されたときにInterruptedExceptionがスローされませんでした

class CheckTimer extends Thread 
{ 

    /** indicate whether the thread should be running */ 
    private volatile boolean running = true; 

    /** Thread that may be interrupted */ 
    private Thread thread; 

    private int duration; 
    private int length; 

    public CheckTimer(int length, Thread thread) 
    { 
     this.duration = 0; 
     this.thread = thread; 
     this.length = length; 
    } 


    /** Performs timer specific code */ 
    public void run() 
    { 
     // Keep looping 
     while(running) 
     { 
      // Put the timer to sleep 
      try 
      { 
       Thread.sleep(100); 
      } 
      catch (InterruptedException ioe) 
      { 
       break; 
      } 

      // Use 'synchronized' to prevent conflicts 
      synchronized (this) 
      { 
       // Increment time remaining 
       duration += 100; 

       // Check to see if the time has been exceeded 
       if (duration > length) 
       { 
        // Trigger a timeout 
        thread.interrupt(); 
        running = false; 
       } 
      } 
     } 
    } 
} 

class Thread1 extends Thread { 
    public void run() { 
     while(true) { 
      System.out.println("thread1 is running..."); 
     } 
    } 
} 

public class Test { 
    public static void main(String[] args) { 
     Thread thread1 = new Thread1(); 
     CheckTimer timer = new CheckTimer(300, thread1); 

     timer.start(); 
     thread1.start(); 

     try { 
      thread1.join(); 
     } catch (InterruptedException e) { 
      e.printStackTrace(); 
     } 
    } 
} 
+0

(thread1.interrupt 'への呼び出し)'どこでもあなたの例ではありません。 –

答えて

1

いいえ、それは今どのように動作するはずです。

Thread1が中断されているかどうかを確認してから、自分で例外をスローする必要があります。

たとえば、例外はThread.sleep()で使用されていますが、実装方法は以下のコードと似ています。

例:その上

if (Thread.interrupted()) { 
    throw new InterruptedException(); 
} 

詳細情報:Interrupted Exception Article

関連する問題