Thread Prevention can also be done using sleep method. If a thread does not want to perform any operation for a specific amount of time, then we should go for sleep method. Sleep method causes thread execution to pause for the specified period of time.
We will understand in detail about sleep method in this article.
The sleep method has two following prototypes:
- public static native void sleep(long milliseconds) – native sleep method having non-java implementation. the thread will sleep for the specified amount of time in milliseconds.
- public static void sleep(long milliseconds, int nanoseconds) – sleep method having an implementation in Java. The thread will sleep for the specified accurate time in milliseconds and nanoseconds.
Any thread while in sleeping state can be interrupted by some other thread. Therefore, every sleep method throws an interrupted exception which is checked exception. Hence, while using sleep method, we should compulsorily handle interrupted exception either by either a try-catch block or by throws keyword. Otherwise, we will get compile time error.
Impact of sleep method on the lifecycle of a thread
Thread.sleep() method interacts with the thread scheduler and puts the current thread in the waiting state for a specified period of time. Once the specified wait time is over, thread state is changed to runnable state and thread then waits for the CPU for further execution. So, the actual time that current thread sleeps depend on the thread scheduler which is part of the operating system.
Let’s understand the usage of sleep method through one example. Look at the code below which calculates time and prints on the screen the time that has been elapsed so far.
// Main class public class TimeCalculator { public static void main(String args[]) throws InterruptedException { for(int i=2;i<=20;i+=2) { // thread goes into sleeping state for 2 seconds Thread.sleep(2000); System.out.println(i + " seconds have passed"); } } }
When we run the above program, thread goes into the sleep state for 2 seconds iteratively inside the loop. Hence, it will calculate 2 seconds time and after every 2 seconds, it will print the statement saying how much time has been elapsed. Look at the output of this program to understand in a better way.
Output:
2 seconds have passed 4 seconds have passed 6 seconds have passed 8 seconds have passed 10 seconds have passed 12 seconds have passed 14 seconds have passed 16 seconds have passed 18 seconds have passed 20 seconds have passed
This is all about the sleep method of java in multi-threading. Hope you find this tutorial helpful.