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

前端 未结 3 1600
情书的邮戳
情书的邮戳 2020-12-10 15:37

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         


        
相关标签:
3条回答
  • 2020-12-10 15:46

    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

    0 讨论(0)
  • 2020-12-10 15:58

    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.

    0 讨论(0)
  • 2020-12-10 16:06

    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.

    0 讨论(0)
提交回复
热议问题