我試圖根據TimeUnit.timedWait(Object, long)實施Future.get(long, TimeUnit)。如何在不失去納秒精度的情況下使用TimeUnit.timedWait()?
目前還不清楚如何使用TimeUnit.timedWait(Object, long)
來處理虛假喚醒而不會丟失TimeUnit的納秒組件。通常你會這樣做:
public V get(long timeout, TimeUnit unit)
{
long expirationTime = new Date().getTime() + unit.toMillis(timeout);
while (!condition)
{
long timeLeft = expirationTime - new Date().getTime();
if (timeLeft <= 0)
throw new TimeoutException();
unit.timedWait(object, timeLeft);
}
}
但你失去了納秒組件。如果每個人都放棄納秒分量,那麼TimeUnit
甚至可以支持納秒並提供TimeUnit.timedWait()
?
你能澄清一下你擔心虛假喚醒的情況嗎?代碼中是否有某些東西使得很難清楚誰在控制對象Monitor? – 2009-12-29 17:00:41
我很確定誰在控制對象Monitor。虛假喚醒指的是即使沒有人調用notify()或發生超時,wait()操作也可能返回。 – Gili 2009-12-29 20:08:19