前面的Guarded Suspension Pattern和Balking Pattern都比較極端。一個是“不讓?爺不玩了”,另一個是“不行!我一定要玩!”。而,Guarded Timeout Patter就中庸的多了,是“現在不讓玩?那我等等吧。如果超過我等待的時間了,我就不玩了”。 還是以代碼說話:
class A{
private long timeout; //等待的最長時間
public synchronized void changeState(){
改變狀態 通知等待的線程不同再等了(notify/notifyAll)
}
public synchronized void guardedMethod() throws InterruptedException{
long start = System.currentTimeMillis(); //開始時刻
while(條件成立不成立){
long now = System.currentTimeMillis(); //現在時刻
long rest = timeout - (now -start); //還需要等待的時間
if(rest <= 0){throw new InterruptedException("...");} //如果為等待時間為0或者為負數,就不等了。
等著一段時間吧,如果超過我等待的最長時間了,我就不玩了(wait(rest)) //當wait的時間超過rest時,也會拋出InteruptedException。
}
進行處理
}
}
在通常情況下,會對if(rest<=0){...}中拋出的異常進行一下包裝,即繼承InterruptedException異常,是得調用者知道是超時了(wait(rest),interrupt方法都可能會拋出InterruptedException,所以必須包裝一下,讓上層程序識別)。
參考: 《Java多線程設計模式》,中國鐵道出版社,2005,結城浩
文章來源:
http://localhost/wp2/?p=88