Listing 8: File Cancel2.java: Illustrates a daemon thread

// Illustrates a Daemon Thread

import java.io.*;

class Counter implements Runnable
{
   private int count = 0;
   
   public void run()
   {
      for (;;)
      {
         System.out.println(count++);
         try
         {
            Thread.sleep(1000);
         }
         catch (InterruptedException x){}
      }
   }
}

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

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

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

Exiting main
*/
— End of Listing —