🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (178K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
The Thread.sleep() method in Java is used to pause the execution of the currently executing thread for a specified period.
Table of Contents
- Introduction
sleep()Method Syntax- Understanding
sleep() - Examples
- Basic Usage with
sleep(long millis) - Using
sleep(long millis, int nanos) - Using
sleep(Duration duration)
- Basic Usage with
- Real-World Use Case
- Conclusion
Introduction
The Thread.sleep() method causes the currently executing thread to pause its execution for a specified duration. This is useful for managing thread execution and simulating delays in a program.
sleep() Method Syntax
There are three overloaded versions of the sleep() method:
sleep(long millis)
public static void sleep(long millis) throws InterruptedException
Causes the currently executing thread to sleep for the specified number of milliseconds.
sleep(long millis, int nanos)
public static void sleep(long millis, int nanos) throws InterruptedException
Causes the currently executing thread to sleep for the specified number of milliseconds plus the specified number of nanoseconds.
sleep(Duration duration)
public static void sleep(Duration duration) throws InterruptedException
Causes the currently executing thread to sleep for the specified duration.
Parameters:
millis: The length of time to sleep in milliseconds.nanos: 0-999999 additional nanoseconds to sleep.duration: The duration to sleep.
Throws:
InterruptedExceptionif any thread has interrupted the current thread.
Understanding sleep()
The Thread.sleep() method pauses the current thread for the specified time. The actual sleep time may be longer due to thread scheduling delays or shorter if the thread is interrupted.
Examples
Basic Usage with sleep(long millis)
To demonstrate the basic usage of sleep(long millis), we will create a thread that sleeps for a specified time.
Example
public class SleepExample {
public static void main(String[] args) {
Thread thread = new Thread(() -> {
System.out.println("Thread is going to sleep for 2 seconds...");
try {
Thread.sleep(2000); // Sleep for 2 seconds
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
System.out.println("Thread has woken up.");
});
thread.start();
try {
thread.join(); // Wait for the thread to finish
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
System.out.println("Main thread resumes after thread completion.");
}
}
Output:
Thread is going to sleep for 2 seconds...
Thread has woken up.
Main thread resumes after thread completion.
Using sleep(long millis, int nanos)
To demonstrate the usage of sleep(long millis, int nanos), we will create a thread that sleeps for a specified time including nanoseconds.
Example
public class SleepMillisNanosExample {
public static void main(String[] args) {
Thread thread = new Thread(() -> {
System.out.println("Thread is going to sleep for 2 seconds and 500000 nanoseconds...");
try {
Thread.sleep(2000, 500000); // Sleep for 2 seconds and 500000 nanoseconds
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
System.out.println("Thread has woken up.");
});
thread.start();
try {
thread.join(); // Wait for the thread to finish
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
System.out.println("Main thread resumes after thread completion.");
}
}
Output:
Thread is going to sleep for 2 seconds and 500000 nanoseconds...
Thread has woken up.
Main thread resumes after thread completion.
Using sleep(Duration duration)
To demonstrate the usage of sleep(Duration duration), we will create a thread that sleeps for a specified duration using the Duration class.
Example
import java.time.Duration;
public class SleepDurationExample {
public static void main(String[] args) {
Thread thread = new Thread(() -> {
System.out.println("Thread is going to sleep for 3 seconds...");
try {
Thread.sleep(Duration.ofSeconds(3)); // Sleep for 3 seconds
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
System.out.println("Thread has woken up.");
});
thread.start();
try {
thread.join(); // Wait for the thread to finish
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
System.out.println("Main thread resumes after thread completion.");
}
}
Output:
Thread is going to sleep for 3 seconds...
Thread has woken up.
Main thread resumes after thread completion.
Real-World Use Case
Simulating Delays
In real-world scenarios, the Thread.sleep() method can be used to simulate delays, such as waiting for resources, simulating network latency, or pacing the execution of a program.
Example
public class DelayedTaskExample {
public static void main(String[] args) {
Runnable task = () -> {
System.out.println("Starting a time-consuming task...");
try {
Thread.sleep(5000); // Simulate a 5-second task
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
System.out.println("Task completed.");
};
Thread thread = new Thread(task);
thread.start();
try {
thread.join(); // Wait for the task to complete
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
System.out.println("Main thread resumes after task completion.");
}
}
Output:
Starting a time-consuming task...
Task completed.
Main thread resumes after task completion.
Conclusion
The Thread.sleep() method in Java provides a way to pause the execution of the current thread for a specified period. By understanding how to use this method and its overloaded versions, you can manage thread execution effectively and simulate delays in your Java applications. Whether you are working with single-threaded or multi-threaded environments, the sleep() method offers a valuable tool for controlling thread behavior and timing.
My Top and Bestseller Udemy Courses. The sale is going on with a 70 - 80% discount. The discount coupon has been added to each course below:
Build REST APIs with Spring Boot 4, Spring Security 7, and JWT
[NEW] Learn Apache Maven with IntelliJ IDEA and Java 25
ChatGPT + Generative AI + Prompt Engineering for Beginners
Spring 7 and Spring Boot 4 for Beginners (Includes 8 Projects)
Available in Udemy for Business
Building Real-Time REST APIs with Spring Boot - Blog App
Available in Udemy for Business
Building Microservices with Spring Boot and Spring Cloud
Available in Udemy for Business
Java Full-Stack Developer Course with Spring Boot and React JS
Available in Udemy for Business
Build 5 Spring Boot Projects with Java: Line-by-Line Coding
Testing Spring Boot Application with JUnit and Mockito
Available in Udemy for Business
Spring Boot Thymeleaf Real-Time Web Application - Blog App
Available in Udemy for Business
Master Spring Data JPA with Hibernate
Available in Udemy for Business
Spring Boot + Apache Kafka Course - The Practical Guide
Available in Udemy for Business
Comments
Post a Comment
Leave Comment