Listing 9: Uses Thread.interrupt to kill a thread

import java.io.*;

class Counter extends Thread
{
   private int count = 0;
   
   public void run()
   {
      while (!interrupted())
      {
         System.out.println(count++);
         try
         {
            Thread.sleep(1000);
         }
         catch (InterruptedException x)
         {
            interrupt();
         }
      }
      System.out.println("Counter Finished");
   }
}

class Interrupt
{
   public static void main(String[] args)
   {
      System.out.println("Press Enter to Cancel:");
      Counter c = new Counter();
      c.start();

      try
      {
         System.in.read();
      }
      catch (IOException x)
      {
         System.out.println(x);
      }
      c.interrupt();
      System.out.println("Exiting main");
   }
}

/* Output:
Press Enter to Cancel:
0
1
2

Exiting main
Counter Finished
*/
— End of Listing —