简体   繁体   English

Java:如何在wait()中区分虚假唤醒和超时

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

Here is a case where a thread is waiting for notify() or a timeout. 这是线程正在等待notify()或超时的情况。 Here a while loop is added to handle spurious wake up. 这里添加了while循环来处理虚假唤醒。

boolean dosleep = true;
while (dosleep){
    try {
        wait(2000);
        /**
         * Write some code here so that
         * if it is spurious wakeup, go back and sleep.
         * or if it is timeout, get out of the loop. 
         */

    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

In this case how can I distinguish between a spurious wake up and time out? 在这种情况下,如何区分虚假唤醒和超时? If it is a spurious wake up, i need to go back and wait. 如果是虚假的唤醒,我需要回去等待。 And if it is a timeout, i need to get out of the loop. 如果超时,我需要退出循环。

I can easily identify the case of notify(), because i will be setting the dosleep variable to false while notify() call. 我可以轻松识别出notify()的情况,因为我将在notify()调用时将dosleep变量设置为false。

EDIT: i am using 1.4 java version, due to embedded project requirement. 编辑:由于嵌入式项目的要求,我正在使用1.4 Java版本。 I cannot use Condition as it is available only post 1.5. 我无法使用Condition因为它仅在1.5后可用。

Thanks in advance. 提前致谢。

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. 这在Java 1.4中应该可以正常工作,并且可以确保线程休眠至少2000ms。

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. 也就是说,丹尼斯建议使用Condition类是执行此操作的更好方法。

I believe Lock s and Condition will better fit your need in this case. 我相信LockCondition在这种情况下会更好地满足您的需求。 Please check the javadocs for Condition.awaitUntil() - it has an example of usage 请检查javadocs中的Condition.awaitUntil() -它有一个用法示例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM