Example: Ending a thread using a Java program

This example shows how to end a thread in a Java™ program.

Note: By using the code examples, you agree to the terms of the Code license and disclaimer information.
/*
FileName: ATEST12.java
 
The output of this example is as follows:
 Entered the testcase
 Create a thread
 Start the thread
 Wait for the thread to complete
 Thread: End with success
 Check the thread status
 Testcase completed
*/
import java.lang.*;
 
 
public class ATEST12 {
 
   static class theThread extends Thread {
      public final static int THREADFAIL = 1;
      public final static int THREADPASS = 0;
      int         _status;
 
      public int status() {
         return _status;
      }
      public theThread() {
         _status = THREADFAIL;
      }
      public void run() {
         System.out.print("Thread: End with success\n");
         _status = THREADPASS;
         /* End the thread without returning    */
         /* from its initial routine            */
         stop();
         System.out.print("Thread: Didn't expect to get here!\n");
         _status = THREADFAIL;
      }
   }
 
   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 for the thread to complete\n");
      try {
         t.join();
      }
      catch (InterruptedException e) {
         System.out.print("Join interrupted\n");
      }
      System.out.print("Check the thread status\n");
      if (t.status() != theThread.THREADPASS) {
         System.out.print("The thread failed\n");
      }
 
      System.out.print("Testcase completed\n");
      System.exit(0);
   }
 
}