Listing 7: File Cancel.java: Stops a thread (but not safely — see Listing 11)

import java.io.*;

class Counter implements Runnable
{
   private int count = 0;
   private boolean cancelled = false;
   
   public void run()
   {
      while (!cancelled)
      {
         System.out.println(count++);
         try
         {
            Thread.sleep(1000);
         }
         catch (InterruptedException x){}
      }
      System.out.println("Counter Finished");
   }
   void cancel()
   {
      cancelled = true;
   }
}

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

      try
      {
         System.in.read();
      }
      catch (IOException x)
      {
         System.out.println(x);
      }
      c.cancel();      // Don't forget this!
      System.out.println("Exiting main");
   }
}

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

Exiting main
Counter Finished
*/
— End of Listing —