Java Thread interrupt Example

In this article, we will learn how to interrupt a running thread in multi-threading applications.

Thread.interrupt() method Overview

An interrupt is an indication to a thread that it should stop what it is doing and do something else. It's up to the programmer to decide exactly how a thread responds to an interrupt, but it is very common for the thread to terminate.
java.lang Thread class provides three interrupt() methods to work Interrupts properly.
  1. void interrupt() - Interrupts this thread.
  2. static boolean interrupted() - Tests whether the current thread has been interrupted.
  3. boolean isInterrupted() - Tests whether this thread has been interrupted.

Thread.interrupt() Method Example

Tasks can be terminated by using the Thread.interrupt() method on the thread. Note that the task will not terminate immediately as terminating the task depends on the execution reaches the line "if (Thread.interrupted())".
public class TerminateTaskUsingThreadAPI {

    public static void main(final String[] args) {

        System.out.println("Thread main started");

        final Task task = new Task();
        final Thread thread = new Thread(task);
        thread.start();

        thread.interrupt();

        System.out.println("Thread main finished");
    }
}

class Task implements Runnable {
  @Override
  public void run() {
    for (int i = 0; i < 5; i++) {
         System.out.println("[" + Thread.currentThread().getName() + "] Message " + i);

         if (Thread.interrupted()) {
              System.out.println("This thread was interruped by someone calling this Thread.interrupt()");
              System.out.println("Cancelling task running in thread " + Thread.currentThread().getName());
              System.out.println("After Thread.interrupted() call, JVM reset the interrupted value to: " + Thread.interrupted());
              break;
         }
     }
  }
}
Output:
Thread main started
Thread main finished
[Thread-0] Message 0
This thread was interruped by someone calling this Thread.interrupt()
Cancelling task running in thread Thread-0
After Thread.interrupted() call, JVM reset the interrupted value to: false
Note that the here the task is being terminated, not the thread.

Reference

Comments