Here is a case where a thread is waiting for notify() or a timeout. Here a while loop is added to handle spurious wake up.
boolean dosleep = true;
while (do
I believe Lock
s and Condition
will better fit your need in this case. Please check the javadocs for Condition.awaitUntil()
- it has an example of usage
You need to keep track of your timeout if you want to distinguish the two cases.
long timeout = 2000;
long timeoutExpires = System.currentTimeMillis() + timeout;
while(dosleep) {
wait(timeout);
if(System.currentTimeMillis() >= timeoutExpires) {
// Get out of loop
break;
}
}
That said, denis's recommendation of using the Condition
class is the better way to do this.
You could do this:
boolean dosleep = true;
long endTime = System.currentTimeMillis() + 2000;
while (dosleep) {
try {
long sleepTime = endTime - System.currentTimeMillis();
if (sleepTime <= 0) {
dosleep = false;
} else {
wait(sleepTime);
}
} catch ...
}
That should work fine in Java 1.4, and it will ensure that your thread sleeps for at least 2000ms.