Java: how to distinguish between false awakening and timeout while waiting ()

Here is a case where a thread is waiting for a notification () or timeout. This adds a while loop to handle false wakeups.

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 false awakening and timeout? If this is a false awakening, I need to go back and wait. And if it's a timeout, I need to exit the loop.

I can easily determine the case of notify (), because I will set the dosleep variable to false when notify () is called.

EDIT: I am using version 1.4 of java because of the built-in project requirement. I cannot use Condition since it is only available after 1.5.

Thanks in advance.

+6
source share
3 answers

You need to keep track of your timeout if you want to distinguish between two cases.

 long timeout = 2000; long timeoutExpires = System.currentTimeMillis() + timeout; while(dosleep) { wait(timeout); if(System.currentTimeMillis() >= timeoutExpires) { // Get out of loop break; } } 

However, a denis recommendation to use the Condition class is the best way to do this.

+4
source

You can do it:

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

This should work fine in Java 1.4, and it ensures that your thread will sleep at least 2000 ms.

+6
source

I believe that Lock and Condition will better suit your needs in this case. Check javadocs for Condition.awaitUntil() - it has a usage example

+4
source

Source: https://habr.com/ru/post/901788/


All Articles