Interrupting a Thread in Java
Last Updated :
11 Jul, 2024
In Java Threads, if any thread is in sleeping or waiting state (i.e. sleep() or wait() is invoked), calling the interrupt() method on the thread, breaks out the sleeping or waiting state throwing InterruptedException. If the thread is not in the sleeping or waiting state, calling the interrupt() method performs normal behavior and doesn’t interrupt the thread but sets the interrupt flag to true.
interrupt() method: If any thread is in sleeping or waiting for a state then using the interrupt() method, we can interrupt the execution of that thread by showing InterruptedException. A thread that is in the sleeping or waiting state can be interrupted with the help of the interrupt() method of Thread class.
Example: Suppose there are two threads and If one of the threads is blocked in an invocation of the wait(), wait(long), or wait(long, int) methods of the Object class, or of the join(), join(long), join(long, int), sleep(long), or sleep(long, int), methods of this class, then its interrupt status will be cleared and it will receive an InterruptedException, which gives the chance to another thread to execute the corresponding run() method of another thread which results into high performance and reduces the waiting time of the threads.
Different scenarios where we can interrupt a thread
Case 1: Interrupting a thread that doesn’t stop working: In the program, we handle the InterruptedException using try and catch block, so whenever any thread interrupts the currently executing thread it will come out from the sleeping state but it will not stop working.
Java
// Java Program to illustrate the
// concept of interrupt() method
// while a thread does not stops working
class MyClass extends Thread {
public void run()
{
try {
for (int i = 0; i < 5; i++) {
System.out.println("Child Thread executing");
// Here current threads goes to sleeping state
// Another thread gets the chance to execute
Thread.sleep(1000);
}
}
catch (InterruptedException e) {
System.out.println("InterruptedException occur");
}
}
}
class Test {
public static void main(String[] args)
throws InterruptedException
{
MyClass thread = new MyClass();
thread.start();
// main thread calls interrupt() method on
// child thread
thread.interrupt();
System.out.println("Main thread execution completes");
}
}
OutputMain thread execution completes
Child Thread executing
InterruptedException occur
Case 2: Interrupting a thread that stops working: In the program, after interrupting the currently executing thread, we are throwing a new exception in the catch block so it will stop working.
Java
// Java Program to illustrate the
// concept of interrupt() method
// while a thread stops working
class Geeks extends Thread {
public void run()
{
try {
Thread.sleep(2000);
System.out.println("Geeksforgeeks");
}
catch (InterruptedException e) {
throw new RuntimeException("Thread " +
"interrupted");
}
}
public static void main(String args[])
{
Geeks t1 = new Geeks();
t1.start();
try {
t1.interrupt();
}
catch (Exception e) {
System.out.println("Exception handled");
}
}
}
Output
Exception in thread "Thread-0" java.lang.RuntimeException: Thread interrupted
at Geeks.run(File.java:13)
Case 3: Interrupting a thread that works normally: In the program, there is no exception occurred during the execution of the thread. Here, interrupt only sets the interrupted flag to true, which can be used by Java programmers later.
Java
// Java Program to illustrate the concept of
// interrupt() method
class Geeks extends Thread {
public void run()
{
for (int i = 0; i < 5; i++)
System.out.println(i);
}
public static void main(String args[])
{
Geeks t1 = new Geeks();
t1.start();
t1.interrupt();
}
}
Similar Reads
Inter-thread Communication in Java
Inter-thread communication in Java is a mechanism in which a thread is paused from running in its critical section, and another thread is allowed to enter (or lock) the same critical section to be executed. Note: Inter-thread communication is also known as Cooperation in Java. What is Polling, and W
6 min read
Java Daemon Thread
In Java, daemon threads are low-priority threads that run in the background to perform tasks such as garbage collection or provide services to user threads. The life of a daemon thread depends on the mercy of user threads, meaning that when all user threads finish their execution, the Java Virtual M
6 min read
ReadWriteLock Interface in Java
A lock is a device for commanding access to an assigned resource by multiple threads. Usually, a lock grants exclusive access to a shared resource: just one thread at a flash can acquire the lock and everyone accesses to the shared resource requires that the lock be acquired first. Though, some lock
3 min read
Main thread in Java
Java provides built-in support for multithreaded programming. A multi-threaded program contains two or more parts that can run concurrently. Each part of such a program is called a thread, and each thread defines a separate path of execution.When a Java program starts up, one thread begins running i
4 min read
Joining Threads in Java
java.lang.Thread class provides the join() method which allows one thread to wait until another thread completes its execution. If t is a Thread object whose thread is currently executing, then t.join() will make sure that t is terminated before the next instruction is executed by the program. If th
3 min read
Java Thread.activeCount() Method
Thread.activeCount() method is a static method of the Thread class in Java that returns the number of active threads in the current thread's thread group and its subgroups. It provides an estimate of how many threads are currently active and being executed in the program, including threads from any
3 min read
Java Thread Class
Thread is a line of execution within a program. Each program can have multiple associated threads. Each thread has a priority which is used by the thread scheduler to determine which thread must run first. Java provides a thread class that has various method calls to manage the behavior of threads b
5 min read
Thread Interference and Memory Consistency Errors in Java
Java allows multithreading which involves concurrent execution of two or more parts of the program. It enhances CPU utilization by performing multiple tasks simultaneously. The threads communicate with each other by sharing object references and member variables. When Two threads access the same sha
5 min read
Java Thread.enumerate() Method
Thread.enumerate() method in Java is used to retrieve all active threads in the current thread's thread group, and it stores these threads in an array. This method provides a way to inspect the currently running threads in a program. It is a static method in the Thread class, which means it can be c
3 min read
Multithreading in Java
Multithreading is a Java feature that allows the concurrent execution of two or more parts of a program for maximum utilization of the CPU. Each part of such a program is called a thread. So, threads are lightweight processes within a process. Different Ways to Create ThreadsThreads can be created b
3 min read