2012-11-03 65 views
1

什麼時候thread.sleep生成InterruptedException?我正在使用這個,但異常沒有發生。請幫助使用線程。關於將信息傳遞給線程並從線程返回信息。 公共類MyThread的繼承Thread {當從Thread.sleep拋出InterruptedException?

@Override 
public void run(){ 

    try{ 

    while(true) { 
     Thread.sleep(200); 
     System.out.println("Thread is running"); 

    } 
    } 
    catch(InterruptedException ex){ 
    System.out.println("Exception Occur"); 
    } 
} 

例外的200ms後不會發生。爲什麼??

+2

從這裏開始:http://docs.oracle.com/javase/tutorial/essential/concurrency/index.html – home

+0

請問您可以發表一些代碼嗎? – BRabbit27

+0

總有[InterruptedException的文檔](http://docs.oracle.com/javase/7/docs/api/java/lang/InterruptedException.html)哪些(除其他外)引用['Thread .interrupt'](http://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html#interrupt())。 –

回答

4

據我所知,當你試圖殺死/中斷正在休眠的線程時會產生InterruptedException。

4

InterruptedException響應Thread.interrupt被調用的Thread實例管理您調用sleep的線程。您可以通過自己調用該方法輕鬆進行測試,即使在您撥打sleep的同一線程中也是如此。只需在Thread.currentThread().interrupt()之前打電話,看看會發生什麼。

相關問題