2016-09-23 107 views
-1

我創建了兩個類,CheckTimer用於在傳遞0.3秒時中斷thread1。我注意到thread.interrupted()被執行CheckTimer.run(),但InterruptedException在主函數中沒有被拋出,thread1繼續運行沒有任何停止提示,爲什麼?是不是thread1.interrupted()應該停止thread1當線程被中斷時不會拋出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

相關問題