Java: How to distinguish between spurious wakeup and timeout in wait()

风格不统一 提交于 2019-11-28 11:12:05

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.

I believe Locks and Condition will better fit your need in this case. Please check the javadocs for Condition.awaitUntil() - it has an example of usage

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!