Search code examples
javawaittime-wait

waiting for infinte time when timeout is given


I have a test code for wait(timeout).

public static void main(String[] args) throws Exception
{
    Runnable r = new Runnable()
    {

        public void run()
        {
            while (true)
            {
                int random = (int)(Math.random() * 10);

                synchronized(this)
                {
                    try
                    {
                        wait(random);
                    }
                    catch (InterruptedException e)
                    {
                        e.printStackTrace();
                    }
                }
                System.out.println(random);
            }
        }
    };

    new Thread(r).start();
}

But, this seems to to not working properly, ideally it should wait for certain time given by random method and print it. But every time it stops after printing several values(random number of times).

Not able to identify what the problem is.


Solution

  • Key to your question lies in java doc of wait which states as follows :-

    The specified amount of real time has elapsed, more or less. If timeout is zero, however, then real time is not taken into consideration and the thread simply waits until notified.

    So, if random return 0, it goes into infinite wait till get notified, which is clearly not happening in your code.

    Better add if check for random == 0.