Difference between Sleep and Wait method in Java
1. Class belongs : The wait() method belongs to java.lang.Object class, thus can be called on any Object. The sleep() method belongs to java.lang.Thread class, thus can be called on Threads.
1. Class belongs : The wait() method belongs to java.lang.Object class, thus can be called on any Object. The sleep() method belongs to java.lang.Thread class, thus can be called on Threads.
2. Context : The wait() method can only be called from Synchronized context i.e. using synchronized block or synchronized method. The sleep() method can be called from any context.
3. Locking : The wait() method releases the lock on an object and gives others chance to execute. The sleep() method does not releases the lock of an object for specified time or until interrupt.
4. Wake up condition : A waiting thread can be awake by notify() or notifyAll() method. A sleeping can be awaked by interrupt or time expires.
5. Execution : Each object has each wait() method for inter-communication between threads. The sleep() method is static method belonging to Thread class. There is a common mistake to write t.sleep(1000) because sleep() is a class method and will pause the current running thread not t.
Recap : Difference between Sleep and Wait in Java
Sleep | Wait | |
---|---|---|
Class belongs | java.lang.Thread | java.lang.Object |
Context | Called from any context | Only synchronized context |
Locking | Does not release the lock for specified time or until interrupt. | Releases the lock |
Wake up Condition | When time expires or due to interruption | Awake by call to notify() or notifyAll() method |
Execution | Execution of sleep will pause the current running thread not the object on which it is called. | Thread wait() continues till a specific condition holds true |
No comments:
Post a Comment