Listing 11: File Cancel3.java: Illustrates a synchronized block

import java.io.*;

class Counter implements Runnable
{
   private int count = 0;
   private boolean cancelled = false;

   public void run()
   {
      for (;;) // Loop must not be synchronized!
      {
         synchronized(this)
         {
            System.out.println(count++);
            if (cancelled)
               break;
         }
         try
         {
            Thread.sleep(1000);
         }
         catch (InterruptedException x){}
      }
      System.out.println("Counter Finished");
   }
   public synchronized void cancel()
   {
      cancelled = true;
   }
}

class Cancel3
{
   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

Exiting main
2
Counter Finished
*/
— End of Listing —