Java - A Thread Interrupting Another Thread

Introduction

In the following code one thread will interrupt another thread.

It counts when the thread is in interrupted state.

Demo

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

    // Let the main thread sleep for 1 second
    try {
      Thread.currentThread().sleep(1000);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
    // Now interrupt the thread
    t.interrupt();
  }

  public static void run() {
    int counter = 0;

    while (!Thread.interrupted()) {
      counter++;
    }
    System.out.println("Counter:" + counter);
  }
}

Result

Related Topic