簡體   English   中英

線程暫停睡眠后會發生什么?

[英]What happens after a thread is paused with sleep?

我有以下代碼

try{
    sleep(500);
}catch(InterruptedException e){}

當線程完成睡眠或在該線程上調用interrupt方法時,會引發InterruptedException嗎?

不,在正常流程期間不會引發InterruptedException ,但是可能在線程上調用interrupt()時發生(例如,其他一些試圖中斷該線程正常執行流程的代碼)。 通常,執行只是在sleep語句之后的行中繼續執行。

如果在睡眠時間內調用了interrupt方法。 catch僅與try代碼相關,此后無效。

如果線程被中斷,則可能會在睡眠期間發生或之前發生中斷,則拋出InterruptedException。 在大多數情況下,當您不期望InterruptedException並且不想處理它時,最好

try{
    sleep(500);
}catch(InterruptedException e){
    Thread.currentThread().interrupt();
}

因此中斷不會丟失。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM