Introduction
As developers, understanding the nuances between different methods is essential for writing efficient and effective code. When it comes to thread synchronization in Java, the wait() and sleep() methods are two critical tools in our toolbox.
While they may seem similar, there are essential differences between these two methods that can have a significant impact on your code's behavior. This article will offer you an in-depth difference between wait and sleep in Java, their syntax, and code examples, along with output to clarify their differences.
Introduction to Sleep() method
Java uses the sleep() function to suspend a thread's execution for a predetermined period of time. This technique is time-dependent and has nothing to do with synchronizing threads. Regardless of whether any other threads are active, a thread will suspend its execution for the duration of the call to sleep(). The thread does not, however, release the lock while it is sleeping, preventing other threads from accessing the locked object.
Let's discuss some important points regarding the Sleep() method:
- Used to pause the execution of a thread for a set period of time.
- During sleep, the thread does not release the lock.
- The interrupt() method allows for interruptions.
- If the thread is interrupted while it is sleeping, it throws an InterruptedException.
Syntax
try{
// Sleeping thread for a specified period
Thread.sleep(time);
}
catch(InterruptedException e){
// Exception handling
}
Example
Let's see an example of the same.
Code
public class Demo{
public static void main(String[] args) throws InterruptedException{
System.out.println("Sleeping for 5 seconds...");
Thread.sleep(5000);
System.out.println("Waking up...");
}
}
Output
Explanation
In the above example, the thread will wait five seconds before performing the subsequent command. The sleep() method is used in this example of Java code to pause a thread's execution for 5 seconds before continuing. The program prints "Waking up..." once the thread is paused for 5 seconds by the Thread.sleep(5000) call. If the thread is interrupted while it is dozing, the InterruptedException is thrown.