wait() vs sleep() in Java: What to Choose for Threads?

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

wait() vs sleep() in Java: Battle of the Multithreading Titans

\n\n

Imagine you are an orchestra conductor. You have violinists (threads) who need to play in harmony, but sometimes they need to wait for others to finish their part. In Java, there are two powerful tools for managing such pauses: wait() and sleep(). At first glance, they seem similar — both cause a thread to "freeze" for a time. But in reality, they are completely different mechanisms, and confusing them is a surefire way to get a deadlock or race condition.

\n\n

This article is your guide through the jungle of multithreading. We won't just list the differences; we'll break them down with live examples so you'll always remember: sleep is a pause, while wait is a release of a resource. Let's go!

\n\n

What is sleep()? (Thread.sleep)

\n\n

The Thread.sleep(milliseconds) method is the simplest way to "put the current thread to sleep" for a specified time. The thread simply rests without releasing object locks. It's like a lazy cat napping on the couch but still holding a toy with its paw.

\n\n

Important facts about sleep():

\n
    \n
  • It is a static method of the Thread class.
  • \n
  • The thread does not release the monitors (locks) it holds.
  • \n
  • After the timer expires, the thread transitions to the Runnable state (ready to execute).
  • \n
  • It can throw InterruptedException.
  • \n
\n\n

A simple example:

\n
public class SleepExample {\n    public static void main(String[] args) throws InterruptedException {\n        System.out.println("Starting: " + System.currentTimeMillis());\n        Thread.sleep(2000); // sleep for 2 seconds\n        System.out.println("Awake: " + System.currentTimeMillis());\n    }\n}
\n\n

Result: There will be exactly 2 seconds between the two outputs. The thread simply waited, doing nothing.

\n\n

What is wait()? (Object.wait)

\n\n

The wait() method is not just a pause, but a mechanism for inter-thread communication. It is defined in the Object class and can only be called inside a synchronized block (synchronized). When a thread calls wait(), it:

\n
    \n
  • Releases the object's monitor (i.e., releases the lock).
  • \n
  • Transitions to the WAITING or TIMED_WAITING state (if a timeout is specified).
  • \n
  • Waits until another thread calls notify() or notifyAll() on the same object.
  • \n
\n\n

This is like saying: "I'm putting down my fork and waiting for the second course to be brought to me." You're not just sleeping — you're freeing up a seat at the table for someone else.

\n\n

A basic example:

\n
public class WaitNotifyExample {\n    private static final Object lock = new Object();\n\n    public static void main(String[] args) throws InterruptedException {\n        Thread waiter = new Thread(() -> {\n            synchronized (lock) {\n                try {\n                    System.out.println("Waiter thread is waiting...");\n                    lock.wait(); // releases lock and waits\n                    System.out.println("Waiter thread received notification!");\n                } catch (InterruptedException e) {\n                    Thread.currentThread().interrupt();\n                }\n            }\n        });\n\n        Thread notifier = new Thread(() -> {\n            synchronized (lock) {\n                System.out.println("Chef thread is cooking...");\n                try {\n                    Thread.sleep(1000); // simulate cooking\n                } catch (InterruptedException e) {\n                    Thread.currentThread().interrupt();\n                }\n                lock.notify(); // wakes up the waiting thread\n                System.out.println("Chef notified the waiter!");\n            }\n        });\n\n        waite                

Blogs

Book Recommendations