取消匿名TimerTask

时间:2015-01-04 02:43:06

标签: java multithreading

boolean timing = true; /* this is a global attribute and its only here for context */
Timer t = new Timer();
t.schedule(new TimerTask() {
        @Override
        public void run() {
            Platform.runLater(() -> {
                new Thread(() -> {
                    if (!timing) {
                        try {
                            tt.cancel(); /* I want to cancel this if timming is false*/
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    } else {
                        update();
                    }
                }).run();
            });
        }
}, 10, 10);

我想知道是否有可能取消其内部的特定TimerTask,请注意“tt”只是一个例子,我不知道还有什么可以称之为。感谢。

2 个答案:

答案 0 :(得分:0)

Timer有自己的后台主题。除非你的任务需要很长时间才能运行,否则你不需要在任务的#run()方法中创建一个新线程(你不应该)。

您可以通过制作实例final

来取消计时器的后续执行
final Timer t = new Timer();
t.schedule(new TimerTask() {
    @Override
    public void run() {
        // Do work.
        if (!timing) {
            t.cancel();
        }
    }
});

(为简洁省略了异常处理。)

如果您只想取消任务本身(允许计时器安排的其他任务继续运行),则可以轻松调用任务实例的#cancel()方法:

if (!timing) {
    this.cancel();
}

您还应确保声明timing变量volatile。如果不这样做,则可以在每个线程中缓存该值,并且您将无法观察到更改。

答案 1 :(得分:0)

如何制作取消Timer的新方法?

private void cancelTimer(Timer t)
{
    t.cancel();
}

您还需要进行Timer决赛。