# The difference between wait and sleep

wait and sleep can both be used to put a thread into sleep and wait for a while. So what’s the difference? To find it out, we need to figure out how to use them first.

# Wait

To use wait, you have to put mon.wait() and mon.notify() inside the synchronized block, where mon is the monitor object. mon is used such that only one thread can enter the synchronized block. It’s easier to see it with the code.

Output:

Here the girl needs to wear the make-up before going out to see the boy. When she finishes, mon.notify() is called and the boy stops waiting, and they meet in the end.

# Sleep

sleep can also be used to put a thread into sleep for a while, and you can use thread.interrupt() to cancel the sleep and put the thread into running. Let’s see an example.

Output:

The girl takes 3 seconds to wear her make-up, and when it’s done, she tells the boy to stop sleeping by calling boyThread.interrupt(), the boy stops sleeping and they meet in the end.

# Difference

So what’s the difference?

1. wait should be used in a synchronized block, while sleep doesn’t need to.
2. wait belongs to java.lang.Object and is an instance method, while sleep belongs to java.lang.Thread and is a static method.
3. wait can be woken by notify, notifyAll and interrupt, while sleep can only be woken by interrupt.
4. wait and notify release the lock, which means you can enter the synchronized block for multiple times as long as those threads call wait, while sleep doesn’t release the lock.

# Use Cases

sleep is a normal way to put the thread into sleep for a pre-defined time, and interrupt is only a way to cancel the sleep.

wait is a normal way for inter-thread communication, and usually you can build a publish-subscribe system by it. notify => publish, wait => subscribe. When you call notify, it means some messages are available, and one thread will be woken to consume those messages.

Share