Thread.sleep() in Java
The method
sleep() is being used to halt the working of a thread for a given amount of
time. The time up to which the thread remains in the sleeping state is known as
the sleeping time of the thread. After the sleeping time is over, the thread
starts its execution from where it has left.
Points
to Remember About the Sleep() Method
- Whenever the Thread.sleep() methods execute, it always halts the execution of the current thread.
- Whenever another thread does interruption while the current thread is already in the sleep mode, then the InterruptedException is thrown.
- If the system that is executing the threads is busy, then the actual sleeping time of the thread is generally more as compared to the time passed in arguments. However, if the system executing the sleep() method has less load, then the actual sleeping time of the thread is almost equal to the time passed in the argument.
Example 01:
package com.java.Multi_threading;
public class SleepExample {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
System.out.println("Countdown: " + i);
try {
// Pause the current thread for 1 second (1000 milliseconds)
Thread.sleep(1000);
} catch (InterruptedException e) {
// Handle the exception if interrupted while sleeping
e.printStackTrace();
}
}
System.out.println("Time's up!");
}
}
0 Comments