Java TimerTask不取消(Java TimerTask not canceling)

编程入门 行业动态 更新时间:2024-10-28 15:25:13
Java TimerTask不取消(Java TimerTask not canceling)

当我在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); } }

最满意答案

它适用于我 - 使用您发布的代码,我看到:

checking status checking status checking status cancel

......没有别的,显示TimerTask已被取消 - 它永远不会再次执行。

当你没有更多的工作要做时,你是否期望Timer本身关闭? 它不会自动执行此操作。 目前尚不清楚你的更大目标是什么,但避免这种情况的一个选择是让TimerTask也取消Timer - 这将起作用,但它在设计方面并不是非常好,并且意味着TimerTask无法在内部运行良好包含其他任务的计时器。

It works for me - using exactly the code you posted, I saw:

checking status checking status checking status cancel

... 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 the TimerTask also cancel the Timer - that will work, but it's not terribly nice in terms of design, and means that the TimerTask can't run nicely within a timer which contains other tasks.

更多推荐

本文发布于:2023-07-28 12:08:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1305175.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Java   TimerTask   canceling

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!