Interrupt a thread. : Suspend resume « Thread « Java Tutorial






class MyThread implements Runnable {
  public void run() {
    try {
      Thread.sleep(30000);
      for (int i = 1; i < 10; i++) {
        if (Thread.interrupted()) {
          System.out.println("interrupted.");
          break;
        }
      }
    } catch (Exception exc) {
      System.out.println(Thread.currentThread().getName() + " interrupted.");
    }
    System.out.println(Thread.currentThread().getName() + " exiting.");
  }
}

public class Main {
  public static void main(String args[]) throws Exception {
    Thread thrd = new Thread(new MyThread(), "MyThread #1");
    Thread thrd2 = new Thread(new MyThread(), "MyThread #2");
    thrd.start();
    Thread.sleep(100);
    thrd.interrupt();
    thrd2.start();
    Thread.sleep(400);
    thrd2.interrupt();
  }
}








10.12.Suspend resume
10.12.1.Suspending and resuming a thread the modern way.
10.12.2.Interrupt a thread.