Key Difference – sleep vs wait in Java
Sleep and wait are two methods used for multithreading in Java. The sleep method belongs to Thread class while the wait method is from the Object class. The key difference between sleep and wait in Java is that, the sleep is used to suspend the execution of the current thread for the specified number of milliseconds while the wait method is used to cause the current thread to wait until another thread invokes the notify or notifyAll method for the object.
A thread is the smallest unit of processing in the operating system. It is a single sequential flow of control within a program. Threads are lightweight. Multithreading is the mechanism of running multiple threads at the same time. Programming languages such as Java supports multithreading. Multithreading has advantages because it allows to run multiple threads simultaneously and the threads are independent of each other. There are methods in Java that can be used for multithreading. Two of them are sleep and wait.
1. Overview and Key Difference
2. What is sleep in Java
3. What is wait in Java
4. Similarities Between sleep and wait in Java
5. Side by Side Comparison – sleep vs wait in Java in Tabular Form
What is sleep in Java?
There are multiple processes running in an operating system. A process is a program in execution. Each process can have multiple threads, and there is a context switching occurring between these threads. In Java, there are two ways to create a thread. That is by extending the thread class or by implementing Runnable interface. The Thread class has constructors and methods to create and perform operations on a thread. The Thread class extends Object class and implements Runnable interface. The Runnable interface should be implemented by any class whose instances are intended to be executed by a thread. When the thread executes, the code that should execute is written inside the run method. The thread that should run is selected by the thread scheduler. Only one thread runs in a single process.
A thread goes through several phases. After creating an object of Thread class, the programmer can invoke the start method. Before invoking that method, the thread is said to be in the new state. The thread scheduler selects a thread to run. If the thread is not yet selected by the thread scheduler but if the start method is invoked, then the thread is in a runnable state. After thread scheduler selects the thread to execute, it transits to running state. If the thread is alive but not currently eligible to run, then it is in non-runnable or blocked state. After the completion of the run method, the thread goes to the terminated state. Those are the main phases of the thread life cycle.
There are various methods available in the thread class to perform different tasks. The sleep method is used to sleep the method for a specific amount of time. The syntax for the sleep method is public void sleep (long milliseconds) throws InterruptedException. It causes the currently executing thread to stop execution temporary for a specified number of milliseconds. If another thread interrupts the current thread, the interrupted status of the current thread is cleared when this exception is thrown.
According to the above program, the run method contains code that should be executed. In the main program, two objects of the ExampleThread1 is created, and the start methods are invoked on them. That will allow to run the code inside the run method. Only one thread executes at a time. With the Thread. sleep (1000); will allow the first thread to terminate the execution for 1000 milliseconds. When a thread is sleeping, the thread scheduler picks up the other thread.
What is wait in Java?
Multiple threads might access a shared resource. It can cause to generate an incorrect output. Thread synchronization can be used to make only one thread to access the shared resource. Assume a situation as follows. If, there are two threads as t1 and t2, t1 start saving values to a text file called Text1.txt. Those values will be used for some other calculation when t1 returns. If t2 starts before t1 returns, t2 can change the values saved by t1. This can cause t1 to provide a wrong output. With the help of synchronization, when t1 starts using the Text1.txt file, that file can be locked, so it is accessible only by t1. The t2 cannot change it until t1 releases the lock to access that text file. When the task is completed the t1 can release the lock. The lock is also known as the monitor.
Thread synchronization can be achieved by inter-thread communication. A critical section is a code segment which accesses the shared resources. In the inter-thread communication, a thread is paused running in its critical section, and another thread is allowed to enter in the same critical section to be executed. It is implemented using wait, notify and notifyAll methods. They belong to the Object class. The wait method is used to allow the current thread to release the lock and wait until another thread invokes the notify or notifyAll method for the object. The notify method is used to wake up a single thread that is waiting for the lock. The notifyAll wakes up all threads that are waiting on the lock.
The Calculator class extends the Thread. The synchronized block is inside the run method. The for loop and notify method is inside the synchronized block. Inside the main method, an instance of a thread created and the start method is called on that instance. The main method will wait till the thread give a notification. When executing the program, the main method waits till the entire execution of the run method and waits for the notify method. Once the notify method is called, the main method stop waiting and starts executing the rest of the code. Main is waiting till the Calculator thread is completed. Finally, the result of the sum is printed.
If there is no synchronized block and if the main method has a code as below, it will give the output as zero because it is not waiting for the other thread to complete.
Calculator t1 = new Calculator ();
t1. start ();
What is the Similarity Between sleep and wait in Java?
- Both sleep and wait are methods that can be used when implementing multithreading in Java
What is the Difference Between sleep and wait in Java?
sleep vs wait in Java
|The sleep method causes the current thread to suspend execution for the specified number of milliseconds, subject to the precision and accuracy of system timers and schedulers.||The wait method causes the current thread to wait until another thread invokes the notify or notifyAll method for the object.|
|Association with Lock|
|The sleep method does not release the lock on an object during synchronization.||The wait method releases the lock during synchronization.|
|Method of Execution|
|The sleep method is executed on the current thread.||The wait method is called on the object.|
|The sleep is a method of Thread class.||The wait is a method of Object class.|
|The sleep process is completed after the specified amount of time is over.||The wait method is interrupted by calling the notify or notifyAll methods.|
Summary – sleep vs wait in Java
There are multiple processes running on the operating system. Each process can have multiple threads. A thread is the smallest unit of processing in an operating system. Java programing language supports multithreading. It allows running multiple threads simultaneously. The sleep and wait are two method that can be used when implementing multi-threading. The difference between sleep and wait in Java is that, the sleep is used to suspend the execution of the current thread for the specified number of milliseconds while the wait method is used to cause the current thread to wait until another thread invokes the notify or notifyAll method for the object.