Java Thread interrupt() Method Example

Java Thread Examples


This post describes the usage of the Java Thread interrupt() method with an example.

Java 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.

Java Thread interrupt() Method Example

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