🎓 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.interrupt() method in Java is used to interrupt a thread.
Table of Contents
- Introduction
interrupt()Method Syntax- How Thread Interruption Works
- Examples
- Basic Usage
- Handling InterruptedException
- Checking Interrupt Status
- Real-World Use Case
- Conclusion
Introduction
The Thread.interrupt() method is used to interrupt a thread that is currently executing. Interrupting a thread sets its interrupt status, which can be checked using the isInterrupted() method or the static interrupted() method. Interruption is commonly used to signal a thread to stop its execution or to handle cleanup tasks.
interrupt() Method Syntax
The syntax for the interrupt() method is as follows:
public void interrupt()
Returns:
- This method does not return a value.
Throws:
SecurityExceptionif the current thread cannot modify the target thread.
How Thread Interruption Works
When a thread is interrupted, its interrupt status is set to true. If the thread is blocked in a call to wait(), sleep(), or join(), it will receive an InterruptedException, and its interrupt status will be cleared. Otherwise, the thread's interrupt status remains set.
Examples
Basic Usage
To demonstrate the basic usage of interrupt(), we will create a thread and interrupt it while it is running.
Example
public class InterruptExample {
public static void main(String[] args) {
Thread thread = new Thread(() -> {
while (!Thread.currentThread().isInterrupted()) {
System.out.println("Thread is running...");
try {
Thread.sleep(1000); // Simulate work
} catch (InterruptedException e) {
System.out.println("Thread was interrupted during sleep.");
Thread.currentThread().interrupt(); // Preserve the interrupt status
}
}
System.out.println("Thread is exiting.");
});
thread.start();
try {
Thread.sleep(3000); // Let the thread run for a while
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
thread.interrupt();
}
}
Output:
Thread is running...
Thread is running...
Thread is running...
Thread was interrupted during sleep.
Thread is exiting.
Handling InterruptedException
When a thread is interrupted while it is blocked, it receives an InterruptedException. You can handle this exception to perform cleanup tasks or stop the thread gracefully.
Example
public class HandleInterruptedExceptionExample {
public static void main(String[] args) {
Thread thread = new Thread(() -> {
try {
while (true) {
System.out.println("Thread is running...");
Thread.sleep(1000); // Simulate work
}
} catch (InterruptedException e) {
System.out.println("Thread was interrupted.");
}
System.out.println("Thread is exiting.");
});
thread.start();
try {
Thread.sleep(3000); // Let the thread run for a while
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
thread.interrupt();
}
}
Output:
Thread is running...
Thread is running...
Thread is running...
Thread was interrupted.
Thread is exiting.
Checking Interrupt Status
You can check a thread's interrupt status using the isInterrupted() method or the static interrupted() method.
Example
public class CheckInterruptStatusExample {
public static void main(String[] args) {
Thread thread = new Thread(() -> {
while (true) {
if (Thread.currentThread().isInterrupted()) {
System.out.println("Thread was interrupted, exiting...");
break;
}
System.out.println("Thread is running...");
try {
Thread.sleep(1000); // Simulate work
} catch (InterruptedException e) {
System.out.println("Thread was interrupted during sleep.");
break;
}
}
});
thread.start();
try {
Thread.sleep(3000); // Let the thread run for a while
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
thread.interrupt();
}
}
Output:
Thread is running...
Thread is running...
Thread is running...
Thread was interrupted during sleep.
Thread was interrupted, exiting...
Real-World Use Case
Stopping Threads Gracefully
In a real-world scenario, you might want to stop a long-running thread gracefully, ensuring that it completes any necessary cleanup tasks.
Example
public class GracefulShutdownExample {
public static void main(String[] args) {
Runnable task = () -> {
while (!Thread.currentThread().isInterrupted()) {
System.out.println("Performing task...");
try {
Thread.sleep(1000); // Simulate work
} catch (InterruptedException e) {
Thread.currentThread().interrupt(); // Preserve the interrupt status
}
}
System.out.println("Cleaning up resources...");
System.out.println("Thread is exiting.");
};
Thread workerThread = new Thread(task);
workerThread.start();
try {
Thread.sleep(5000); // Let the thread run for a while
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
workerThread.interrupt();
}
}
Output:
Performing task...
Performing task...
Performing task...
Performing task...
Cleaning up resources...
Thread is exiting.
Conclusion
The Thread.interrupt() method in Java provides a way to interrupt a thread and signal it to stop its execution or handle cleanup tasks. By understanding how to use this method, you can manage the lifecycle of threads more effectively in your Java applications. Whether you are handling long-running tasks, managing resources, or ensuring graceful shutdowns, the interrupt() method offers used for controlling thread execution in Java.
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