title: Why does this java timer sample never end
body: <p>I was looking for a Java timer sample and found the code below at 
  <a href="http://www.javaprogrammingforums.com/java-se-api-tutorials/883-how-use-timer-java.html" rel="nofollow">http://www.javaprogrammingforums.com/java-se-api-tutorials/883-how-use-timer-java.html</a></p>
  
  <p>But if you run the sample, although it does print Timer stops now... it does not return to the command prompt.  This is at least what is happening on my Windows XP machine using cmd.exe.</p>
  
  <p>Why does it not return control to the prompt in this case?</p>
  
  <pre><code>import java.util.Timer;
  import java.util.TimerTask;
  
  public class TimerSample {
  
      public static void main(String[] args) {
          //1- Taking an instance of Timer class.
          Timer timer = new Timer("Printer");
  
          //2- Taking an instance of class contains your repeated method.
          MyTask t = new MyTask();
  
  
          //TimerTask is a class implements Runnable interface so
          //You have to override run method with your certain code black
  
          //Second Parameter is the specified the Starting Time for your timer in
          //MilliSeconds or Date
  
          //Third Parameter is the specified the Period between consecutive
          //calling for the method.
  
      timer.schedule(t, 0, 2000);
  
      }
  }
  
  class MyTask extends TimerTask {
      //times member represent calling times.
      private int times = 0;
  
  
      public void run() {
          times++;
          if (times &lt;= 5) {
              System.out.println("I'm alive...");
          } else {
              System.out.println("Timer stops now...");
  
              //Stop Timer.
              this.cancel();
          }
      }
  }
  </code></pre>