Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

wait()/wait(timeout)/sleep(timeout)?

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) ?

like image 871
JavaUser Avatar asked Jul 08 '10 02:07

JavaUser


People also ask

What is difference between sleep () and wait ()?

Difference between wait() and sleep() The major difference is that wait() releases the lock while sleep() doesn't release any lock while waiting. wait() is used for inter-thread communication while sleep() is used to introduce a pause on execution, generally.

What is wait () in Java?

In java, synchronized methods and blocks allow only one thread to acquire the lock on a resource at a time. So, when wait() method is called by a thread, then it gives up the lock on that resource and goes to sleep until some other thread enters the same monitor and invokes the notify() or notifyAll() method.

How do you wait for time out?

wait(long timeout) causes current thread to wait until either another thread invokes the notify() method or the notifyAll() method for this object, or a specified amount of time has elapsed. The current thread must own this object's monitor.


1 Answers

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.
like image 184
Borealid Avatar answered Sep 21 '22 06:09

Borealid