java timer的cancel()调用后为什么没停止?

2025-03-25 03:56:25
推荐回答(2个)
回答1:

/**
* Cancels the {@code Timer} and all scheduled tasks. If there is a
* currently running task it is not affected. No more tasks may be scheduled
* on this {@code Timer}. Subsequent calls do nothing.
*/
public void cancel() {
impl.cancel();
}

这个Timer.class中关于cancel()的注释,也就是说当有running task时,他不会起作用的。你想要停止该TimerTask,应该使用的是task.cancel().

回答2:

这个问题我也碰到了 我建议还是用插旗法做逻辑控制 就是说 你的定时任务肯定是要执行你想要的逻辑代码 当你调用取消以后 你去把逻辑状态改变一下 然后任务代码里 先判断这个逻辑状态在去执行 这样就算任务没有停止 进入代码以后 有个逻辑判断 这样也不会执行你真正想要执行的代码了