Killing threads in Java

JavaServer Side ProgrammingProgramming

Example

 Live Demo

public class Main{
   static volatile boolean exit = false;
   public static void main(String[] args){
      System.out.println("Starting the main thread");
      new Thread(){
         public void run(){
            System.out.println("Starting the inner thread");
            while (!exit){
            }
            System.out.println("Exiting the inner thread");
         }
      }.start();
      try{
         Thread.sleep(100);
      }
      catch (InterruptedException e){
         System.out.println("Exception caught :" + e);
      }
      exit = true;
      System.out.println("Exiting main thread");
   }
}

Output

Starting the main thread
Starting the inner thread
Exiting main thread
Exiting the inner thread

The main class creates a new thread, and calls the ‘run’ function on it. Here, a Boolean value is defined, named ‘exit’, that is set to false initially. Outside a while loop, the ‘start’ function is called. In the try block, the newly created thread sleeps for a specific amount of time after which the exception would be caught, and relevant message would be displayed on the screen. After this, the main thread will be exited since the value of exit will be set to ‘true’.

raja
Published on 14-Jul-2020 06:59:44
Advertisements