gpt4 book ai didi

java - 取消匿名TimerTask

转载 作者:行者123 更新时间:2023-12-03 13:12:24 24 4
gpt4 key购买 nike

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”只是一个例子,我不知道该怎么称呼它。谢谢。

最佳答案

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。否则,该值可能会缓存在每个线程中,并且您将无法观察到更改。

关于java - 取消匿名TimerTask,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27761848/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com