Difference between wait() and sleep() in Java

January 16, 2017

In this short post, we will discuss the difference between wait() and sleep().

In simple words sleep() hold on the process in memory for specified time while wait() releases the monitor and keeps “waiting” until calling the notify() method.

Wait() is used when we want to communicate between specified threads. Sleep() is just for mere pause for a thread.

1. Sleep

Thread.sleep(n) means that we send it into “timed waiting” state for n time where is a number of milliseconds (or even nanoseconds if we want to, the method has got 2 arguments then). For example, when n = 10000 it means it will be waiting for 10 000 milliseconds (which is 10 seconds).

Another crucial thing about sleep() is that it’s a static method. We can use it only for the current thread and for that one it will be affected. We cannot sleep() thread other than current one.

However, we can release the sleeping thread from another one (and of course from the current one) using thread_name.interrupt() method as you can see in this short example:

Afterward, it is the time to show more complex example:

This code prints:

2. Wait

This method is very similar to the previous one although we use it for an object. This kind of object is needed for thread synchronization, and we name it “lock object”.

And now lock.wait() sends the thread to “waiting” state and make space for other processes to execute. Actually, lock.wait() moves it to some waiting list. The only way to move it out is to use the notify() or notifyAll() method. This is important because it’s the only way to let the process/thread to work again. The whole synchronization which helps the program with memory management take place in a synchronized method. All of these we will show in the example below.

In the first thread, we can do some instructions, wait for the second process to execute and continue at the exact point when it paused. This is the result of our code:

 

Click here to add a comment

Leave a comment: