sleep() is a static method that is used to send the calling thread into a non-runnable state for the given duration of time. The important part for this is recognizing the “calling thread”, which is actually the thread in which the sleep() method is invoked rather than the thread object which may (which is essentially a violation of Java standards) invoke this method. What this means is, while calling Thread.sleep(<duration in milliseconds>) is appropriate and will send the invoking thread to non-runnable state, but calling t.sleep(<duration in milliseconds>) is inappropriate as it would cause the thread in which this call appears to go to non-runnable state instead of the “t” thread whose object is invoking the method. While in “sleep”, the thread will keep all the monitor locks which it might be holding at the time of sleep invocation.
The t.suspend() method has been deprecated, as it is inherently deadlock-prone.It suspends the thread on which it is invoked. If the target thread holds a lock on the monitor protecting a critical system resource when it is suspended, no thread can access this resource until the target thread is resumed. If the thread that would resume the target thread attempts to lock this monitor prior to calling resume
, deadlock results.
t.wait() 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 difference between sleep() and wait() is that sleep() is called on a thread while wait() is called on an object (That’s why it is part of Object class. The parent to all Java classes). The wait() 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. Later, another thread can synchronize on the same lock object and call lock.notify(). This wakes up the original, waiting thread T.
No comments:
Post a Comment