Java - use wait() method until specific time reached

Viewed 11566

I have a thread that runs in the background of my program and detects when a deadline (set by user input at the beginning of the program) occurs. I have implemented this in a while loop and using the sleep(1000) method.

It all works ok, but I would like to change it over from using sleep(1000) to using wait() and notifyAll() to be consistent with the rest of my code, and to make the alert happen in real-time rather than lagging by a part of a second until the thread re-awakens.

Here is what I currently have

    //Retrieve current date and time...
    Calendar now = Calendar.getInstance();

    //deadline not yet reached
    while(now.before(deadline))
    {
        try
        {
            //wait a second and try again
            sleep(1000);
        }
        catch (InterruptedException intEx)
        {
            //Do nothing.
        }

        //Update current date and time...
        now = Calendar.getInstance();
        //run loop again
    }

    ////////////////////////////
    ///alert user of deadline///
    ////////////////////////////

I have tried to change it over to use wait(), but had no success. Can anybody see a way of changing the existing code over to implement the methods I mentioned?

Thanks in advance, Mark

3 Answers
Related