Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Introduction to Sleep() method
2.1.
Syntax
2.2.
Example
2.2.1.
Code
2.2.2.
Output
2.2.3.
Explanation
3.
Introduction to Wait() method
3.1.
Syntax
3.2.
Example
3.2.1.
Code
3.2.2.
Output
3.2.3.
Explanation
4.
Sleep() Vs Wait()
5.
Frequently Asked Questions
5.1.
Can we call the wait() method without acquiring a lock on the object?
5.2.
Can we interrupt a thread while it is sleeping using the sleep() method?
5.3.
Can the sleep() method be used to wait for a notification from another thread?
5.4.
How can we wake up a thread waiting using the wait() method?
5.5.
Can we use the wait() and sleep() methods together?
6.
Conclusion
Last Updated: Mar 27, 2024
Medium

Difference between Wait and Sleep in Java

Author Surbhi Sharma
0 upvote

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.

difference between wait and sleep in java

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

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.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Introduction to Wait() method

Java's wait() function is used to put a thread's execution on hold until it hears from another thread. This technique, which is used to synchronize threads, is independent of time. A thread enters the waiting state and releases the lock on the object it is presently holding when it invokes the wait() function. Other threads are now able to access the locked object and execute their own commands.

Let's discuss some important points regarding the Wait() method:

  • Used to hold up a thread's progress until it receives a message from another thread.
  • After releasing the lock, the thread moves into the waiting state.
  • It can be woken up by another thread using the notify() or notifyAll() methods.
  • If the thread is interrupted while waiting, it throws an InterruptedException.

Syntax

try{
	// Acquiring lock
	synchronized(object){
		// Calling wait() on the object
		object.wait();
	}
}
catch(InterruptedException e){
	// Exception handling
}


Example

Let's discuss an example to understand better.

Code

class WaitExample{
	public static void main(String[] args) throws InterruptedException{
		final Object lock = new Object();
		System.out.println("Acquiring lock...");
		synchronized(lock){
			System.out.println("Lock acquired...");
			lock.wait();
			System.out.println("Lock released...");
		}
	}
}


Output

output

Explanation

The wait() method is used in this example to release the lock on an object while anticipating a notification from another thread. To print "Lock released...", the program first acquires the lock, uses lock.wait() to release it, and then waits for another thread to provide notice. If the thread is interrupted while waiting, the InterruptedException is thrown.

Sleep() Vs Wait()

Java offers two functions that can be used to suspend a thread's execution: wait() and sleep(). In the following sections, we will know more about the differences between these two methods.

Wait()

Sleep()

Called on object Called on thread
Time independent  Time-dependent
Releases a lock Does not release a lock
It does not require any parameters It requires parameters ( Time to sleep in milliseconds)
It is used for thread synchronization. It is used for thread timing
Requires notification from another thread to resume. Does not require notification to resume.
It must be called within a synchronized block It can be called anywhere in the code

 

Must Read Static Blocks In Java.

Frequently Asked Questions

Can we call the wait() method without acquiring a lock on the object?

No, calling the wait() method requires the thread to acquire the lock on the object.

Can we interrupt a thread while it is sleeping using the sleep() method?

Yes, we can interrupt a thread while it is sleeping utilizing the interrupt() method.

Can the sleep() method be used to wait for a notification from another thread?

No, the sleep() method is time-dependent and does not require any notification to proceed with the execution.

How can we wake up a thread waiting using the wait() method?

We can wake up a thread waiting using the notify() or notifyAll() method.

Can we use the wait() and sleep() methods together?

Yes, using the wait() and sleep() methods together is possible, but it depends on the use case.

Conclusion

In conclusion, the sleep() and wait() methods are two crucial Java techniques for thread synchronization. Despite their apparent similarity, the two approaches differ significantly from one another. While the sleep() function is time-dependent and doesn't need any notice, the wait() method is time-independent and requires notification from another thread. To create Java code that is effective and synchronized, it is essential to comprehend these distinctions. 

So it's time for you now to refer to other articles based on a similar topic:

We hope this blog has helped you enhance your knowledge of the difference between wait and sleep in Java. Do visit here to study the Basics of Java with Data Structures and Algorithms in-depth and clarify all your concepts. 

To learn more about DSA, competitive coding, and many more knowledgeable topics, please look into the guided paths on Coding Ninjas Studio. Also, you can enroll in our courses and check out the mock test and problems available. Please check out our interview experiences and interview bundle for placement preparations.

Happy learning!

Previous article
Synchronization in Java
Next article
Synchronization Block in Java
Live masterclass