Download the BYJU'S Exam Prep App for free GATE/ESE preparation videos & tests - Download the BYJU'S Exam Prep App for free GATE/ESE preparation videos & tests -

Difference between Wait() and Sleep() in Java

Both of these are concepts used in multithreading. In simpler words, the Sleep() and Wait() are the native methods that we can use to make any currently running thread go into a state that is non-runnable. They help pause any process for a few seconds and then make the thread go into a waiting state in the program. But there is a significant difference between Wait() and Sleep() in Java. In this article, we will discuss the same in brief. But before we do that, let us take a look at the Sleep() and Wait() methods individually.

What is Wait() in Java?

The Wait() method of Java gets defined in the object class. It asks the current thread (or the calling thread) to keep waiting until and unless another thread happens to invoke the notifyAll() or notify() method for this very object. In this case, the thread would wait until and unless it obtains the monitor’s ownership again and then resumes its execution.

What is Sleep() in Java?

We use the Sleep() method in Java for pausing the execution of the thread currently running for some specific time. This time is known as sleeping time, and it is calculated in milliseconds. In this case, the thread won’t lose the monitor’s ownership for resuming its execution. It can start the process of execution from exactly where it stopped.

Thus, the Sleep() method sends the currently running thread into a state known as the “Non-Runnable” state.

Difference between Wait() and Sleep() in Java

Let us talk about the differences between Wait() and Sleep() in Java.

Parameters Wait() in Java Sleep() in Java
Class It belongs to the object class. It belongs to the thread class.
Object Lock during Synchronisation The lock on an object is released during synchronisation via the Wait() method. The lock on an object isn’t released when synchronising using the Sleep() method.
Synchronised Context We can only call Wait() from the synchronised context. We need not call Sleep() from the synchronised context.
Static Method The Wait() method is not static. The Sleep() method is static.
Overloaded Methods The Wait() method consists of three overloaded methods, namely:

  • wait (long timeout, int nanos). Here, nanos: Nanoseconds
  • wait (long timeout)
  • wait()
The Sleep() method consists of two overloaded methods, namely:

  • sleep (long millis, int nanos). Here, nanos: Nanoseconds
  • sleep (long millis). Here, millis: Milliseconds

Keep learning and stay tuned to BYJU’S to get the latest updates on GATE Exam along with GATE Eligibility Criteria, GATE 2024, GATE Admit Card, GATE Application Form, GATE Syllabus, GATE Cutoff, GATE Previous Year Question Paper, and more.

Also Explore,

Comments

Leave a Comment

Your Mobile number and Email id will not be published.

*

*