Both wait() and sleep() methods are used to pause the
execution of current thread for some period of time. Whenever a thread calls
wait() method, it goes into WAITING state
after releasing the lock it holds. Whenever a thread calls sleep() method, it
goes into TIMED_WAITING state
without releasing the lock it holds.
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.
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.
No comments:
Post a Comment