Member-only story
Java wait()
vs sleep()
with Examples
4 min read
·
Apr 5, 2025In Java multithreading, both wait()
and sleep()
methods are used to pause the execution of a thread. However, they are completely different in terms of behavior, purpose, and usage.
Understanding the difference between wait()
and sleep()
is essential for writing thread-safe and efficient concurrent code. Let’s explore each method in depth with examples and explain how they differ point by point.
Overview of wait()
and sleep()
What is wait()
?
wait()
is a method of thejava.lang.Object
class.- It is used for inter-thread communication.
- When a thread calls
wait()
, it releases the lock it holds and waits until another thread callsnotify()
ornotifyAll()
on the same object.
What is sleep()
?
sleep()
is a method of thejava.lang.Thread
class.- It is used to pause the current thread for a specific period of time.
- The thread does not release the lock during sleep and resumes automatically after the sleep duration is over.
📊 Comparison Table: wait()
vs sleep()
Let’s go deeper into each point and illustrate it with examples.