我想創建一個可以隨時中斷的執行緒,同時防止虛假喚醒。這里的問題是虛假喚醒和中斷的作業方式相同:它們拋出InterruptedException
void anyMethodCalledByThread() {
// .. a lot of work before
while (wakingUpCondition) {
try {
lock.wait()
} catch (InterruptedException e) {
// is it spurious wake up and I should just ignore it?
// or is it actual interrupt and I should do:
// Thread.interrupt();
// return;
// and check interruption status in methods above to abort all tasks?
}
}
// .. a lot of work after
}
從中我看到,沒有辦法僅僅用jdk來區分它們,甚至Condition
沒有用。我看到的唯一可能的解決方案是為volatile boolean
每個執行緒使用一些額外的東西,但這Thread.interrupt()
本身就變得毫無用處。
uj5u.com熱心網友回復:
虛假喚醒和中斷的作業方式相同:它們拋出 InterruptedException
這不是我的理解。 發生虛假喚醒是因為一個條件在沒有被特別發出信號的情況下被喚醒,并且與InterruptedException
. 當由于實作細節而發出任何條件信號時,某些執行緒系統會喚醒所有條件。虛假喚醒是我們需要定義回圈的原因之一。while
如果該wait()
方法拋出InterruptedException
,那么它就真的被中斷了。
// we use while loop because lock.wait() might return because of spurious wakeup
while (wakingUpCondition) {
try {
lock.wait()
} catch (InterruptedException ie) {
// if the wait was interrupted then we should re-interrupt and maybe quit
Thread.currentThread().interrupt();
// handle the interrupt by maybe quitting the thread?
return;
}
}
順便說一句,我認為我們while
較少使用回圈來處理虛假的喚醒條件(這有點罕見),而更多地用于執行緒競爭條件。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/424567.html
上一篇:讓我發瘋的Pthread資料競賽