What is the Difference Between sleep(), suspend() and wait()

Thread.sleep() takes the current thread to a “Not Runnable” state for specified amount of time. The thread holds the monitors it has acquired. For example, if a thread is running a synchronized block or method and sleep method is called then no other thread will be able to enter this block or method. The sleeping thread can wake up when some other thread calls t.interrupt on it. Note that sleep is a static method, that means it always affects the current thread (the one executing sleep method). A common mistake is trying to call t2.sleep() where t2 is a different thread; even then, it is the current thread that will sleep, not the t2 thread. thread.suspend() is deprecated method. Its possible to send other threads into suspended state by making a suspend method call. In suspended state a thread keeps all its monitors and can not be interrupted. This may cause deadlocks therefore it has been deprecated. object.wait() call also takes the current thread into a “Not Runnable” state, just like sleep(), but with a slight change. Wait method is invoked on a lock object, not thread.

Here is the sequence of operations you can think:

  • A thread T1 is already running a synchronized block with a lock on object – lets say “lockObject”
  • Another thread T2 comes to execute the synchronized block and find that its already acquired.
  • Now T2 calls lockObject.wait() method for waiting on lock to be release by T1 thread.
  • T1 thread finishes all its synchronized block work.
  • T1 thread calls lockObject.notifyAll() to notify all waiting threads that its done using the lock.
  • Since T2 thread is first in the queue of waiting it acquires the lock and starts processing.