Re: [問題] Thread interrupt的問題
※ 引述《recorriendo (孟新)》之銘言:
: 大家好 小弟最近在學Threading
: 關於interrupt 我查了很多地方都沒寫得很清楚
: 所以我寫了下面這個程式
: public class ThreadPlay extends Thread {
: @Override
: public void run() {
: System.out.println(isInterrupted());
: this.interrupt();
: System.out.println(isInterrupted());
: try {
: Thread.sleep(5000);
: } catch (InterruptedException e) {
: e.printStackTrace();
: }
: System.out.println(isInterrupted());
: }
: public static void main(String[] args) {
: ThreadPlay thr = new ThreadPlay();
: thr.start();
: }
: }
: 執行後 三行println印出來分別是false, true, false
: 所以說 interrupt之後isInterrupted()會傳回true
: 但如果有InterruptedException 之後 又會被改回false?
: 請問這是Java原本的設定 還是跟我自己編譯器的解讀有關? 謝謝各位解答
參考資料: Java Tutorial, http://tinyurl.com/cbhukxm
摘錄最後一段
By convention, any method that exits by throwing an InterruptedException
clears interrupt status when it does so. However, it's always possible
that interrupt status will immediately be set again, by another thread
invoking interrupt.
=>在丟出 InterruptedException之後, Interrupt Status 會被重置為 False..
所以這是Java 語言本身的規定, 你的編譯器是如實的執行而已..
雖然 sleep() 函式的運作方式取決於底層 OS, 不過可以這麼理解.
每隔一小段時間, thread 就會起來檢查一下, 有沒有被 interrupted,
如果有則重置 interrupt status, 接著丟出例外, 交回執行權..
檢查的依據就是 interrupt status, 在你的範例中, 已經先呼叫 interrupt
設定 interrupt status = true, 所以 sleep 函式應該是馬上中止執行
,重置 interrupt status = false, 並且丟出例外.
以上...
完畢
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 66.235.2.31
討論串 (同標題文章)
本文引述了以下文章的的內容:
完整討論串 (本文為第 2 之 2 篇):