skip to main |
skip to sidebar
Notes on wait method
- the wait() method causes a thread to release the lock it is holding on an object; allowing another thread to run
- the wait() method is defined in the Object class
- wait() can only be invoked from within synchronized code
- it should always be wrapped in a try block as it throws IOExceptions
- there are actually three wait() methods
- wait()
- wait(long timeout)
- wait(long timeout, int nanos)
- the timeout is measured in milliseconds
- nanos is measured in nanoseconds
- wait() can only invoked by the thread that own's the lock on the object
- when wait() is called, the thread becomes disabled for scheduling and lies dormant until one of four things occur:
- another thread invokes the notify() method for this object and the scheduler arbitrarily chooses to run the thread
- another thread invokes the notifyAll() method for this object
- another thread interrupts this thread
- the specified wait() time elapses
- when one of the above occurs, the thread becomes re-available to the Thread scheduler and competes for a lock on the object
- once it regains the lock on the object, everything resumes as if no suspension had occurred
- if the thread was interrupted by another thread, an InterruptedException is thrown BUT not until after the thread regains it's lock on the object
- the wait() method throws three exceptions
- IllegalArgumentException - if the timeout value passed is invalid
- IllegalMonitorStateException - if the current thread does not own the object's lock
- InterruptedException - if another thread interrupts the current thread. The interrupted status of the current thread is cleared
Courtesy: http://www.janeg.ca/scjp/threads/wait.html
No comments:
Post a Comment