What is difference b/w wait() and sleep() in Java Threading

sleep() is a method which is used to hold the process for few seconds or the time you wanted but in case of wait() method thread goes in waiting state and it won’t come back automatically until we call the notify() or notifyAll().

The major difference is that wait() releases the lock or monitor while sleep() doesn’t releases any lock or monitor while waiting. Wait is used for inter-thread communication while sleep is used to introduce pause on execution, generally.

  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.
life cycle of thread
Wait in Threading

 

When to use wait () – The wait () is used for multithread synchronization, where single resource is shared among multiple thread. Example – File resources over the network.

When to use sleep () – The sleep () is used for time synchronization, where the thread actually need a delay in background. For example process something on specific interval.

You may also like

Leave a Reply

Your email address will not be published. Required fields are marked *