我根据 this article 中的提醒示例测试了一个简单的 Timer 和 TimerTask .
唯一的区别是我在timer.cancel()之前使用条件if。在原始示例中,线程按预期停止,但在我的代码中,它不会停止。怎么了?
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");
}
}
最佳答案
Timer.schedule(TimerTask, long)
安排任务在提供的延迟后执行一次。如果您希望重复,则需要使用 Timer.schedule(TimerTask, long, long)
。例如:
int delay = 0;
int interval = seconds * 1000;
timer.schedule(new RemindTask(), delay, interval);
关于java - 使用条件 TimerTask 不会终止线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34757345/