Explain the difference between wait and sleep in Java in detail

  • 2021-07-07 07:38:21
  • OfStack

1. Overview

In this short article, we'll look at the standard sleep () and wait () methods in the core Java, and see the differences and similarities between them.

2. One general difference between wait and sleep

Simply put, wait () is an instance method for thread synchronization.

It can be called on any object because it is defined on java. lang. Object, but it can only be called from an synchronized block. It releases the lock on the object so that another thread can jump in and acquire the lock.

On the other hand, Thread. sleep () is a static method that can be called from any context. Thread. sleep () pauses the current thread and does not release any locks.

The following is a preliminary understanding of these two core API:


private static Object LOCK = new Object();
 
private static void sleepWaitExamples() 
 throws InterruptedException {
 
 Thread.sleep(1000);
 System.out.println(
  "Thread '" + Thread.currentThread().getName() +
  "' is woken after sleeping for 1 second");
 
 synchronized (LOCK) {
  LOCK.wait(1000);
  System.out.println("Object '" + LOCK + "' is woken after" +
   " waiting for 1 second");
 }
}

Running this example produces the following output:

Thread 'main' is woken after sleeping for 1 second
Object 'java. lang. Object @ 31befd9f' is woken after waiting for 1 second

3. Wake up wait and sleep

When we use the sleep () method, the thread starts after a specified time interval, unless it is interrupted.

For wait (), the wake-up process is a bit complicated. We can wake up the thread by calling the notify () or notifyAll () methods on the waiting monitor.

If you want to wake up all threads that are waiting, use notifyAll () instead of notify (). Similar to the wait () method itself, notify () and notifyAll () must be called from the synchronization context.

For example, you can wait here:


synchronized (b) {
 while (b.sum == 0) {
  System.out.println("Waiting for ThreadB to complete...");
  b.wait();
 }
 
 System.out.println("ThreadB has completed. " + 
  "Sum from that thread is: " + b.sum);
}

Then, this is how another thread wakes up the waiting thread-by calling notify () on the monitor:


int sum;
 
@Override
public void run() {
 synchronized (this) {
  int i = 0;
  while (i < 100000) {
   sum += i;
   i++; 
  }
  notify(); 
 } 
}

Running this example produces the following output:

Waiting for ThreadB to complete …

ThreadB has been completed. The sum of threads is: 704982704

4. Conclusion

This is a quick start to wait and sleep semantics in Java.

In general, we should use sleep () to control the execution time of one thread and wait () for multi-thread synchronization. Of course, after a deep understanding of the basic knowledge, there is still more to explore.


Related articles: