Java:如何在wait()中区分虚假唤醒和超时 [英] Java: How to distinguish between spurious wakeup and timeout in wait()

查看:139
本文介绍了Java:如何在wait()中区分虚假唤醒和超时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是线程正在等待notify()或超时的情况。这里添加了一个while循环来处理虚假唤醒。

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 (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.

我可以轻松识别notify()的情况,因为我会在notify()调用时将dosleep变量设置为false。

I can easily identify the case of notify(), because i will be setting the dosleep variable to false while notify() call.

编辑:由于嵌入式项目要求,我使用的是1.4版java。我不能使用条件,因为它仅在1.5后可用。

i am using 1.4 java version, due to embedded project requirement. I cannot use Condition as it is available only post 1.5.

提前致谢。

推荐答案

如果你想区分这两种情况,你需要跟踪你的超时。

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.

这篇关于Java:如何在wait()中区分虚假唤醒和超时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆