wait() vs sleep() in Java: Battle of the Multithreading Titans
\n\nImagine 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.
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\nWhat is sleep()? (Thread.sleep)
\n\nThe 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.
Important facts about sleep():
- \n
- It is a static method of the
Threadclass. \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
A simple example:
\npublic 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\nResult: There will be exactly 2 seconds between the two outputs. The thread simply waited, doing nothing.
\n\nWhat is wait()? (Object.wait)
\n\nThe 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
- 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()ornotifyAll()on the same object. \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\nA basic example:
\npublic 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