Example: Cancel a thread using Java

This example shows a Java™ program canceling a long-running thread.

Note: By using the code examples, you agree to the terms of the Code license and disclaimer information.
/*
FileName: ATEST13.java
 
The output of this example is as follows:
 Entered the testcase
 Create a thread
 Start the thread
 Wait a bit until we 'realize' the thread needs to be canceled
 Thread: Entered
 Thread: Looping or long running request
 Thread: Looping or long running request
 Thread: Looping or long running request
 Wait for the thread to complete
 Thread status indicates it was canceled
 Testcase completed
*/
import java.lang.*;
 
 
public class ATEST13 {
 
   static class theThread extends Thread {
      public final static int THREADPASS     = 0;
      public final static int THREADFAIL     = 1;
      public final static int THREADCANCELED = 2;
      int         _status;
 
      public int status() {
         return _status;
      }
      public theThread() {
         _status = THREADFAIL;
      }
      public void run() {
         System.out.print("Thread: Entered\n");
         try {
            while (true) {
               System.out.print("Thread: Looping or long running request\n");
               try {
                  Thread.sleep(1000);
               }
               catch (InterruptedException e) {
                  System.out.print("Thread: sleep interrupted\n");
               }
            }
         }
         catch (ThreadDeath d) {
            _status = THREADCANCELED;
         }
      }
   }
 
   public static void main(String argv[]) {
      System.out.print("Entered the testcase\n");
 
      System.out.print("Create a thread\n");
      theThread t = new theThread();
 
      System.out.print("Start the thread\n");
      t.start();
 
      System.out.print("Wait a bit until we 'realize' the thread needs to be canceled\n");
      try {
         Thread.sleep(3000);
      }
      catch (InterruptedException e) {
         System.out.print("sleep interrupted\n");
      }
      t.stop();
 
      System.out.print("Wait for the thread to complete\n");
      try {
         t.join();
      }
      catch (InterruptedException e) {
         System.out.print("Join interrupted\n");
      }
      System.out.print("Thread status indicates it was canceled\n");
      if (t.status() != theThread.THREADCANCELED) {
         System.out.print("Unexpected thread status\n");
      }
 
      System.out.print("Testcase completed\n");
      System.exit(0);
   }
 
}