執行緒基礎3 執行緒中斷

2021-08-28 05:57:11 字數 1049 閱讀 7362

已經過時的方法:

暫停 suspend()

恢復 resume()

停止 stop()

過時原因:

suspend()方法在呼叫後,執行緒不會釋放已經占有的資源(比如鎖),而是占有著資源進入睡眠狀態,這樣容易引發死鎖問題。stop()方法在終結乙個執行緒時不會保證執行緒的資源正常釋放。

執行緒中斷的三個方法:

注意:

執行緒在阻塞的時候才會響應中斷 (比如當前執行緒thread.sleep(100)的時候)

執行緒的interrupt() 方法會丟擲乙個interruptedexception 並且會清除當前執行緒的的中斷標示

執行緒的呼叫 interrupt()中斷後 再呼叫清除方法interrupted() 第一次會返回true 第二次會false

public class threadstop extends thread  catch (interruptedexception e) 

}public static void main(string args)

}

執行結果:

1初始中斷狀態:false

2呼叫後中斷狀態true

3清除中斷標記true

4清除中斷標記後中斷狀態false

5呼叫interrupt後中斷狀態true

7執行緒被終止了interruptedexception 會清除中斷標記 狀態為false

執行緒的中斷可以讓程式設計師自定義的處理中斷從而可以更加靈活的處理當前執行緒中斷時需要處理的資源和業務邏輯 

除了jdk自帶的執行緒中斷我們也可以定義乙個volatile 變數來標示當前執行緒是否要中斷比如

public class threadstop extends thread 

}public static void main(string args)

}

多執行緒 執行緒中斷

設計思路 1,新建乙個執行緒,其啟動引數是要輸出其執行狀態。2,中斷主線程若干秒,讓新建執行緒持續運作。3,中斷新建執行緒,輸出起執行次數和執行狀態。int count 0 thread t2 new thread catch threadabortexception absortexception...

執行緒基礎3

mutex 又稱互斥量,c 11中與 mutex 相關的類 包括鎖型別 和函式都宣告在 標頭檔案中,所以如果你需要使用 std mutex,就必須包含 標頭檔案。mutex 系列類 四種 lock 類 兩種 其他型別 函式下面以 std mutex 為例介紹 c 11 中的互斥量用法。std mut...

多執行緒學習 執行緒中斷

執行緒中斷的方法有 1.stop已廢棄 2.使用共享變數 shared variable 發出訊號,告訴執行緒必須停止正在執行的任務。執行緒必須週期性的核查這一變數,然後有秩序地中止任務。通過volatile關鍵字設定開關 private static class worker extends th...