Java TimerTask 未取消
当我在 run 方法中调用 cancel() 时,我的 CheckStatus (TimerTask) 没有停止。 this.cancel() 也不起作用。我做错了什么?
import java.util.TimerTask;
class CheckStatus extends TimerTask {
int s = 3;
public void run() {
if (s > 0)
{
System.out.println("checking status");
s--;
}
else
{
System.out.println("cancel");
cancel();
}
}
}
这是我的司机
import java.util.*;
class Game {
static Timer timer;
static CheckStatus status;
public static void main(String[] args) throws InterruptedException {
CheckStatus status = new CheckStatus();
timer = new Timer();
timer.scheduleAtFixedRate(status, 0, 3000);
}
}
My CheckStatus (TimerTask) is not stopping when I call cancel() inside the run method. this.cancel() also does not work. What am I doing wrong?
import java.util.TimerTask;
class CheckStatus extends TimerTask {
int s = 3;
public void run() {
if (s > 0)
{
System.out.println("checking status");
s--;
}
else
{
System.out.println("cancel");
cancel();
}
}
}
Heres my driver
import java.util.*;
class Game {
static Timer timer;
static CheckStatus status;
public static void main(String[] args) throws InterruptedException {
CheckStatus status = new CheckStatus();
timer = new Timer();
timer.scheduleAtFixedRate(status, 0, 3000);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
它对我有用 - 完全使用您发布的代码,我看到:
...没有其他内容,表明 TimerTask 已被取消 - 它永远不会再次执行。
您是否期望
Timer
在没有更多工作要做时自行关闭?它不会自动执行此操作。目前尚不清楚您的更大目标是什么,但避免这种情况的一种选择是让 TimerTask 也取消 Timer - 这会起作用,但就术语而言并不是很好设计上的缺陷,意味着TimerTask
无法在包含其他任务的计时器内正常运行。It works for me - using exactly the code you posted, I saw:
... and nothing else, showing that the
TimerTask
has been cancelled - it's never executing again.Were you expecting the
Timer
itself to shut down when it didn't have any more work to do? It doesn't do that automatically. It's not clear what your bigger goal is, but one option to avoid this is to make theTimerTask
also cancel theTimer
- that will work, but it's not terribly nice in terms of design, and means that theTimerTask
can't run nicely within a timer which contains other tasks.您正在调用计时器任务的取消方法,但您应该调用计时器本身的取消方法来获得预期的行为。
you are calling the cancel method of the timer task but you should call the cancel method of the timer itself to get your expected behaviour.