2011-12-06 131 views
2

我有一個關於中斷Java線程的問題。說我有一個RunnableJava - 中斷線程?

public MyRunnable implements Runnable { 
    public void run() { 
     operationOne(); 
     operationTwo(); 
     operationThree(); 
    } 
} 

我想要實現這樣的事情:

Thread t = new Thread(new MyRunnable()); 
t.run(); 

... // something happens 
    // we now want to stop Thread t 

t.interrupt(); // MyRunnable receives an InterruptedException, right? 

... // t is has now been terminated. 

我如何在Java中實現這一點?具體而言,我如何捕獲中的InterruptedException

+0

順便說一句,如果你錯過了我的答案,第二行代碼應該是t.start(),而不是t.run()。 – user949300

回答

2

我建議測試Thread.isInterrupted()。 Javadoc here。這裏的想法是,你正在做一些工作,很可能是在一個循環中。在每次迭代中,您都應該檢查中斷標誌是否爲真,並停止工作。

while(doingWork && !Thread.isInterrupted() { 
    // do the work 
} 

編輯:要清楚,你的線程將不會收到InterruptedException如果子任務沒有阻擋或最壞的,吃的例外。檢查標誌是正確的方法,但不是每個人都遵循它。

+0

如果我需要檢查給定的操作,該怎麼辦? – ryyst

+0

@ryyst您必須在給定的操作過程中檢查 –

+0

您需要檢查每個條件內的條件。如果每個條件都是短暫的,那麼沒有傷害,但如果每個人都在做一些工作,那麼你也應該檢查操作。 –

-1

首先,應該是類存在

public class MyRunnable extends Thread { 
    public void run() { 
     if(!isInterrupted()){ 
      operationOne(); 
      operationTwo(); 
      operationThree(); 
     } 
    } 
} 

將這項工作做得更好?

+1

他不需要'擴展線程',他也應該在運行一,二和三時檢查該標誌。 –

0

我認爲上述答案几乎適合您的問題。我只是想在InterruptedException

的Javadoc補充一下說:

InterruptedException的:當一個線程在等待睡覺時拋出,或 否則停了很長一段時間,而另一個線程使用中斷的方式中斷它 在Thread類中。

這意味着同時運行

operationOne(); 
operationTwo(); 
operationThree(); 

,除非你處於休眠狀態,等待鎖或這三種方法的地方暫停InterruptedException不會被拋出。

編輯如果提供的代碼不能像在這裏提供的好的和有用的答案所提示的那樣改變,那麼恐怕你沒有辦法打斷你的線程。正如C#等其他語言一樣,通過調用Thread.Abort()可以中止線程,Java不具備這種可能性。瞭解更多關於確切原因的信息,請參見link

+0

這些方法的作者可能會考慮多線程並檢查isInterrupted()和/或引發InterruptedException。雖然這應該已經記錄! – user949300

+0

@ user949300剛剛更新了我的答案。請參閱編輯 – GETah

0

InterruptedThreadException僅在線程被阻塞(等待,睡眠等)時拋出。否則,你必須檢查Thread.currentThread().isInterrupted()

1

首先,你的第二塊代碼的第二行應該是t.start(),而不是t.run()。 t.run()只是簡單地調用你的run方法。

是的,MyRunnable.run()必須在Thread.currentThread()。isInterrupted()正在運行時定期檢查。由於你可能想在Runnable中做很多事情涉及InterruptedExceptions,所以我的建議是咬住子彈並與它們一起生活。定期調用效用函數

public static void checkForInterrupt() throws InterruptedException { 
    if (Thread.currentThread().isInterrupted()) 
     throw new InterruptedException(); 
} 

編輯添加

因爲我看到一個評論,招貼擁有單兵作戰無法控制,他MyRunnable.run()的代碼看起來應該像

public void run() { 
    operation1(); 
    checkForInterrupt(); 
    operation2(); 
    checkForInterrupt(); 
    operation3(); 
}