Within Java, the Thread class offers two versions of the sleep method. One version takes a single argument, while the other version takes two arguments. This sleep method is utilized to pause a thread's operation for a specified duration. The duration during which the thread stays in a paused state is referred to as the thread's sleep duration. Once this duration elapses, the thread resumes its execution from the point where it was paused.
What is Thread.sleep?
The Thread.sleep method, part of the Thread class, is a static method that induces the current thread in execution to pause its operation for a designated amount of milliseconds.
The sleep Method Syntax:
Following are the syntax of the sleep method.
public static void sleep(long mls) throws InterruptedException
public static void sleep(long mls, int n) throws InterruptedException
The sleep function with a single parameter is considered a native function, and its implementation is done in a different programming language. In contrast, methods with two parameters are not native functions and are implemented in Java. The sleep functions can be accessed through the Thread class since the sleep functions have the static keyword in their signature. Both native and non-native functions throw a checked Exception, so handling it with a try-catch block or the throws keyword is necessary.
The Thread.sleep function is applicable to all threads, allowing either another thread or the main thread to call the sleep function.
Parameters:
Listed below are the arguments employed in the sleep function.
mls: The time in milliseconds is represented by the parameter mls. The duration for which the thread will sleep is given by the method sleep.
The value of n represents the duration for which the programmer or developer intends for the thread to remain in the sleep state. The permissible range for n spans from 0 to 999999.
The method does not return anything.
Points to Remember
Whenever the Thread.sleep function is called, it causes the current thread to pause its execution.
If a different thread interrupts the current thread while it is already in a sleeping state, the InterruptedException will be raised.
When the system running the threads is under heavy load, the thread's sleep duration tends to exceed the specified time in the arguments. Conversely, when the system executing the sleep function is less burdened, the thread's actual sleep time is nearly equivalent to the time provided in the argument.
Basic Usage of Thread.sleep Method
Here's a simple example of using Thread.sleep:
File Name: SleepExample.java
public class SleepExample {
public static void main(String[] args) {
System.out.println("Start");
try {
Thread.sleep(2000); // Pause for 2000 milliseconds (2 seconds)
} catch (InterruptedException e) {
System.out.println("Thread interrupted");
}
System.out.println("End");
}
}
Output:
Start
End
In this instance, the primary thread displays "Start", takes a break for 2 seconds, and subsequently displays "End".
Handling InterruptedException
An essential consideration when working with Thread.sleep is managing the InterruptedException. This particular exception is raised when a separate thread interrupts the thread that is in a sleeping state. It is vital to appropriately address this exception to ensure the resilience of your application. Below is an illustration:
File Name: InterruptHandling.java
public class InterruptHandling {
public static void main(String[] args) {
Thread thread = new Thread(() -> {
try {
System.out.println("Thread will sleep for 5 seconds.");
Thread.sleep(5000);
System.out.println("Thread woke up after sleep.");
} catch (InterruptedException e) {
System.out.println("Thread was interrupted during sleep.");
}
});
thread.start();
try {
Thread.sleep(2000); // Main thread sleeps for 2 seconds
thread.interrupt(); // Interrupt the sleeping thread
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
Output:
Thread will sleep for 5 seconds.
Thread was interrupted during sleep.
Within this code snippet, the child thread is programmed to pause its execution for a duration of 5 seconds. However, the main thread intervenes and interrupts the child thread's sleep after only 2 seconds have elapsed. The interruption is managed smoothly by the catch block in the code.
Example of the sleep method in Java : on the custom thread
Below is a demonstration illustrating the utilization of the sleep function on a user-defined thread.
FileName: TestSleepMethod1.java
class TestSleepMethod1 extends Thread{
public void run(){
for(int i=1;i<5;i++){
// the thread will sleep for the 500 milli seconds
try{Thread.sleep(500);}catch(InterruptedException e){System.out.println(e);}
System.out.println(i);
}
}
public static void main(String args[]){
TestSleepMethod1 t1=new TestSleepMethod1();
TestSleepMethod1 t2=new TestSleepMethod1();
t1.start();
t2.start();
}
}
Output:
1
1
2
2
3
3
4
4
In a single-threaded environment, only one thread is processed at a time. When a thread is put to sleep for a specific duration, the thread scheduler switches to another thread, allowing it to run, and continues this process with other threads in the queue.
Example of the sleep Method in Java : on the main thread
FileName: TestSleepMethod2.java
// important import statements
import java.lang.Thread;
import java.io.*;
public class TestSleepMethod2
{
// main method
public static void main(String argvs[])
{
try {
for (int j = 0; j < 5; j++)
{
// The main thread sleeps for the 1000 milliseconds, which is 1 sec
// whenever the loop runs
Thread.sleep(1000);
// displaying the value of the variable
System.out.println(j);
}
}
catch (Exception expn)
{
// catching the exception
System.out.println(expn);
}
}
}
Output:
0
1
2
3
4
Example of the sleep Method in Java: When the sleeping time is -ive
In the provided scenario, an IllegalArgumentException is raised if a negative value is passed for the sleep duration.
FileName: TestSleepMethod3.java
// important import statements
import java.lang.Thread;
import java.io.*;
public class TestSleepMethod3
{
// main method
public static void main(String argvs[])
{
// we can also use throws keyword followed by
// exception name for throwing the exception
try
{
for (int j = 0; j < 5; j++)
{
// it throws the exception IllegalArgumentException
// as the time is -ive which is -100
Thread.sleep(-100);
// displaying the variable's value
System.out.println(j);
}
}
catch (Exception expn)
{
// the exception iscaught here
System.out.println(expn);
}
}
}
Output:
java.lang.IllegalArgumentException: timeout value is negative
Use Cases for Thread.sleep Method
Testing and Simulation: The method Thread.sleep is commonly employed during testing to mimic time delays and pauses between actions.
Polling involves the need for regular checks, such as monitoring resources or services, where a method like Thread.sleep can be employed to introduce intervals between these checks.
Rate Limiting is a technique used to prevent a system from being overloaded by a large number of requests. It involves using Thread.sleep to pause between operations, thereby introducing delays in the processing of requests.
Best Practices
Although Thread.sleep can be beneficial, it is advisable to utilize it cautiously. Below are a few recommended approaches:
Prevent Overuse: Excessive reliance on Thread.sleep may result in unresponsive applications. It is advisable to explore other synchronization methods such as wait/notify or more advanced concurrency tools.
Manage Interruptions Effectively: It is crucial to handle the InterruptedException properly in order to allow your application to gracefully recover from interruptions.
Implement Purposeful Pauses: It is essential to set a meaningful duration for sleep and avoid random delays. Random delays can cause inefficiency and unpredictable outcomes.
Limitations
Variability: The effective duration of sleep may extend beyond the specified time frame as a result of system timer accuracy and additional processing time for thread scheduling.
Inappropriate for Synchronization: The method Thread.sleep is not intended for synchronization purposes and should not be utilized for coordinating threads.
Conclusion
To summarize, the Thread.sleep function is a valuable and uncomplicated feature for halting thread operation in Java. It has multiple uses, such as mimicking delays in testing scenarios and enforcing rate limits and regular inspections. Nevertheless, it is crucial to employ it thoughtfully, handling interruptions correctly and exploring other synchronization methods. By grasping how to use it appropriately, recognizing its constraints, and following recommended guidelines, programmers can efficiently employ Thread.sleep to regulate thread timing and supervision within their Java programs.