The Thread.sleep() method in Java allows you to pause the execution of a thread for a given time. This tutorial explains its syntax, usage with loops, and exception handling, along with practical examples. Learn how to safely delay execution, handle interruptions, and understand when to use Thread.sleep() in real-world Java applications.
The Thread.sleep()
method in Java is used to pause the execution of the current thread for a specific amount of time (in milliseconds). This is useful when you want to delay program execution, control thread scheduling, or simulate real-time processing.
Table of contents [Show]
Thread.sleep(milliseconds);
Thread.sleep(milliseconds, nanoseconds);
public class SleepExample {
public static void main(String[] args) {
System.out.println("Program starts...");
try {
Thread.sleep(2000); // pause for 2 seconds
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Program resumes after 2 seconds.");
}
}
Output:
Program starts...
(2-second pause)
Program resumes after 2 seconds.
public class LoopSleepExample {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
System.out.println("Count: " + i);
try {
Thread.sleep(1000); // pause for 1 second each iteration
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
This example pauses the program for one second between each count.
The Thread.sleep()
method throws an InterruptedException
, which must be handled using try-catch
.
public class InterruptedExample {
public static void main(String[] args) {
Thread thread = new Thread(() -> {
try {
System.out.println("Thread going to sleep...");
Thread.sleep(3000);
System.out.println("Thread woke up!");
} catch (InterruptedException e) {
System.out.println("Thread was interrupted!");
}
});
thread.start();
thread.interrupt(); // interrupt before completion
}
}
Thread.sleep()
does not release any locks while sleeping.InterruptedException
properly in multi-threaded applications.Thread.sleep()
for precise timing in production; use ScheduledExecutorService
instead.The Thread.sleep()
method is a simple way to pause execution in Java. It is most commonly used for simulating delays, controlling program flow, or testing multi-threaded behavior. With proper exception handling, it can be an effective tool for Java developers.
Your email address will not be published. Required fields are marked *