Hi,
What is the difference between wait() and wait(timeout).Anyway wait() needs to wait for a notify call but why we have wait(timeout) ?
So what is the difference between sleep(timeout) and wait(timeout) ?
Hi,
What is the difference between wait() and wait(timeout).Anyway wait() needs to wait for a notify call but why we have wait(timeout) ?
So what is the difference between sleep(timeout) and wait(timeout) ?
wait(timeout) will return if the thread is still waiting after the timeout has elapsed. This is for hang notification, for low-power polling, etc etc. Sleep(timeout) won't wake up until the timeout has elapsed; wait(timeout) is either the notify() call or the timeout, whichever comes first.
Quoting from the JavaDoc:
"This method causes the current thread (call it T) to place itself in the wait set for this object and then to relinquish any and all synchronization claims on this object. Thread T becomes disabled for thread scheduling purposes and lies dormant until one of four things happens:
* Some other thread invokes the notify method for this object and thread T happens to be arbitrarily chosen as the thread to be awakened.
* Some other thread invokes the notifyAll method for this object.
* Some other thread interrupts thread T.
* 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."
The only difference between wait()
and wait(timeout)
is that wait()
will never wake up without a notify()
. wait(timeout)
with a timeout > 0 allows you to potentially save yourself from locking up your application "forever" if a call to notify()
never occurs.
wait(timeout): when the timeout expires the thread wakes up and tries to re-acquire the synchronization lock (i.e. if another thread has not notified it within the timeout period).
sleep(timeout): sleep can be used without any sycnhronization code - it just puts the thread to sleep for the specified timeout. Note that wait must be used within synchronized code.
So, wait is used when you expect a thread to be notified by another thread (but may not, hence timeout). And, wait must be called within synchronized code.