Java - Interrupting a Blocked Thread

Introduction

You may interrupt a blocked thread.

A thread may block itself by executing one of the sleep(), wait(), and join() methods.

If a thread blocked is interrupted, an InterruptedException is thrown and the interrupted status of the thread is cleared.

The following code starts a thread that sleeps for one second and prints a message until it is interrupted.

The main thread sleeps for five seconds, so the sleeping thread gets a chance to sleep and print messages a few times.

When the main thread wakes up, it interrupts the sleeping thread.

Demo

public class Main {
  public static void main(String[] args) {
    Thread t = new Thread(Main::run);
    t.start();/*  ww w  .ja va2  s.c  om*/

    // main thread sleeps for 5 seconds
    try {
      Thread.sleep(5000);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }

    // Interrupt the sleeping thread
    t.interrupt();
  }

  public static void run() {
    int counter = 1;
    while (true) {
      try {
        Thread.sleep(1000);
        System.out.println("Counter:" + counter++);
      } catch (InterruptedException e) {
        System.out.println("I got interrupted!");
        // Terminate the thread by returning
        return;
      }
    }

  }
}

Result

Related Topic