2016-01-13 52 views
0

我测试了一个简单的Timer和TimerTask基于this article提醒示例。线程不使用条件TimerTask终止

唯一的区别是我使用条件,如果之前timer.cancel()。在原始示例中,线程按预期停止,但在我的代码中,它不停止。怎么了?

import java.util.Timer; 
import java.util.TimerTask; 

public class ConditionalReminder { 
    Timer   timer; 

    public ConditionalReminder(int seconds) { 
     timer = new Timer(); 
     timer.schedule(new RemindTask(), seconds*1000); 
    } 

    class RemindTask extends TimerTask { 
     int counter; 

     public void run() { 
      counter++; 
      System.out.format("Time's up!%n"); 
      if(counter==100) 
      { 
       timer.cancel(); //should terminate thread 
      } 
     } 
    } 

    public static void main(String args[]) { 
     new ConditionalReminder(2); 
     System.out.format("Task scheduled.%n"); 
    } 
} 
+0

它会永久运行吗?或者只是一次? – Thilo

+0

它永远运行Thilo。 – Dino

回答