Spurious wakeup
一般來說,線程進入休眠狀態,直到下面四種情況發生:
- 其他線程調用被鎖對象的notify方法,喚醒此線程
- 其他線程調用被鎖對象的notifyAll方法,喚醒阻塞的所有線程
- 其他線程調用了此線程的interupt方法
- 指定的時間到了
線程在其他情況下醒來,就叫做虛假喚醒。
官方解釋:
means that when you wait on a condition variable, the wait may (occasionally) return when no thread specifically broadcast or signaled that condition variable. Spurious wakeups may sound strange, but on some multiprocessor systems, making condition wakeup completely predictable might substantially slow all condition variable operations. The race conditions that cause spurious wakeups should be considered rare."
就是說,如果要防止極少發生的虛假喚醒,這樣就會放緩所有條件變量的操作。(如果一定要不發生虛假喚醒的話,就會很慢…)
所以寫程序的話,一定要對虛假喚醒作處理。
舉個例子:
synchronized(obj) {
while(!some_conditions){
obj.wait();
}
}
需要:
- wait方法必須在同步內
- 循環檢測條件是否成立