Interrupt a thread. : Thread Status « Threads « Java






Interrupt a thread.

 

class MyThread implements Runnable {
  public void run() {
    System.out.println(Thread.currentThread().getName() + " starting.");
    try {
      Thread.sleep(30000);
      for (int i = 1; i < 10; i++) {
        if (Thread.interrupted()) {
          System.out.println("interrupted.");
          break;
        }
        System.out.print(".");
        for (long x = 0; x < 1000; x++)
          System.out.println("/");
      }
    } 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(1000);
    thrd.interrupt();
    thrd2.start();
    Thread.sleep(4000);
    thrd2.interrupt();
  }
}

   
  








Related examples in the same category

1.Is thread aliveIs thread alive
2.Thread sleepThread sleep
3.Another way to stop a threadAnother way to stop a thread
4.Another way to suspend and resumeAnother way to suspend and resume
5.Visual suspend and resumeVisual suspend and resume
6.Thread sleep and interruptThread sleep and interrupt
7.Daemon ThreadDaemon Thread
8.Pausing the Current Thread: a thread can temporarily stop execution.
9.Pausing a Thread: set a variable that the thread checks occasionally, call Object.wait()
10.set Uncaught Exception Handler
11.Monitor a thread's status.
12.Pause the execution
13.Stopping a Thread: set a variable that the thread checks occasionally
14.Determining When a Thread Has Finished
15.Add a delay
16.Pause the execution of a thread using sleep()