Interrupting a Thread
Learn how one thread can request another thread to stop waiting and respond to an interruption.
1. A Simple Everyday Example
Imagine a person is sleeping, and you need to wake them up because something important has happened.
You call their name or gently wake them up.
They can then wake up and decide what to do next.
Java provides a similar mechanism for threads.
One thread can send an interruption request to another thread. The other thread can respond to that request.
2. What Is Thread Interruption?
Java provides a method called interrupt()
in the Thread class.
We can use it to request that another thread respond to an interruption.
Let's look at a simple example.
Thread worker = new Thread(() -> {
System.out.println("Worker is running...");
});
worker.start();
worker.interrupt();
Here, we call interrupt() on the worker thread.
But there is something important to understand:
interrupt() does not forcibly stop a thread.
It sends an interruption request. The thread needs to respond to that request appropriately.
3. Interrupting a Thread That Is Sleeping
Let's understand interruption using something we already
know: Thread.sleep().
Suppose a worker thread is sleeping for ten seconds. Meanwhile, the main thread decides to interrupt it.
public class InterruptExample {
public static void main(String[] args)
throws InterruptedException {
Thread worker = new Thread(() -> {
try {
System.out.println("Worker: Going to sleep");
Thread.sleep(10000);
System.out.println("Worker: Finished sleeping");
} catch (InterruptedException e) {
System.out.println("Worker: I was interrupted!");
}
});
worker.start();
Thread.sleep(2000);
worker.interrupt();
}
}
Let's understand what happens.
- The main thread creates and starts the worker thread.
- The worker thread prints its first message.
- The worker thread goes to sleep for ten seconds.
- The main thread waits for two seconds.
- The main thread calls
worker.interrupt(). - The sleeping worker thread receives the interruption and its sleep is ended early.
- The worker thread handles the
InterruptedException.
The output will be similar to:
Worker: Going to sleep
Worker: I was interrupted!
Notice that the worker did not sleep for the full ten seconds. The interruption caused its sleep to end early.
4. Understanding InterruptedException
When a thread is sleeping and another thread interrupts it,
Java throws an exception called
InterruptedException.
We handle this exception using a try-catch
block.
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
System.out.println("Thread was interrupted");
}
The code inside the catch block executes
when the sleeping thread is interrupted.
Remember that InterruptedException is not
an error that we should always ignore. It is a signal
that the thread has received an interruption request.
5. What If the Thread Is Not Sleeping?
This is an important difference.
What happens if we interrupt a thread that is performing normal work instead of sleeping?
In that situation, calling interrupt()
does not automatically stop the thread or throw
InterruptedException.
The thread can check whether it has received an interruption request by using:
Thread.currentThread().isInterrupted()
This method returns:
trueif an interruption request is present.falseif no interruption request is present.
Let's see a simple example.
public class InterruptCheckExample {
public static void main(String[] args)
throws InterruptedException {
Thread worker = new Thread(() -> {
while (!Thread.currentThread().isInterrupted()) {
System.out.println("Worker is doing its work...");
}
System.out.println("Worker received interruption request.");
});
worker.start();
Thread.sleep(100);
worker.interrupt();
}
}
Here, the worker keeps doing its work while it has not received an interruption request.
When the main thread calls worker.interrupt(),
the worker detects the request and exits the loop.
This is an example of a thread responding to interruption by checking its interruption status.
The exact number of messages printed will vary because both threads execute independently.
6. interrupt() vs isInterrupted()
We have now seen two methods. Let's understand the difference.
- interrupt(): Sends an interruption request to a thread.
- isInterrupted(): Checks whether a particular thread has an interruption request.
For example:
worker.interrupt();
boolean interrupted = worker.isInterrupted();
The first statement sends the request. The second statement checks the worker thread's interruption status.
One more useful method is
Thread.interrupted(). It checks the
interruption status of the current thread and clears
that status when it returns the result.
For now, focus mainly on interrupt() and
isInterrupted().
7. What Did We Learn?
interrupt()sends an interruption request to a thread.- It does not forcibly terminate a thread.
- If a sleeping thread is interrupted, it receives an
InterruptedException. - A thread performing normal work can check its interruption status using
isInterrupted(). - A thread should decide how to respond to an interruption request.
The most important thing to remember:
Interruption is a request, not a forceful command to kill a thread.
Test Your Understanding
Let's check what you have learned.
1. Which method is used to send an interruption request to a thread?
2. Does interrupt() forcibly terminate a thread?
3. What happens when a sleeping thread is interrupted?
4. Which method checks the interruption status of a particular thread?
5. What should a thread do when it receives an interruption request?
Class Summary
Let's quickly revise what we learned in this class.
interrupt()sends an interruption request to a thread.- It does not forcibly terminate a thread.
- Interrupting a sleeping thread causes it to receive an
InterruptedException. isInterrupted()checks the interruption status of a particular thread.- A thread should respond appropriately to an interruption request.
Remember: Interruption is a request, not a command to forcibly kill a thread.
You have completed 9 out of 46 classes.