gpt4 book ai didi

java - 定时器:取消正在运行的任务

转载 作者:行者123 更新时间:2023-11-30 09:39:07 28 4
gpt4 key购买 nike

我需要创建一个异步线程,它运行一次,延迟 2 分钟,并且可以随时终止。我看到了几种可能的解决方案:

  1. ScheduledExecutorServiceFutureTask 允许我中断正在运行的任务,但我必须调用 shutdown() 来终止所有正在运行的线程,这将阻止用户直到进程终止。此外,我将不得不频繁调用 Thread.interrupted(),如 Enno Shioji's answer 中所述。 .
  2. TimerTimerTask 不需要释放正在运行的线程,但是我没有办法中断正在运行的定时器线程 (Timer.cancel()只是取消 future 的安排)
  3. 使用Thread and sleepthread interruption问题。

有好的解决办法吗? (我使用的是 tomcat 7)

谢谢

最佳答案

经过一些测试和研究,FutureTask.cancel() 和 Threads 需要类似的中断处理,如 Enno Shioji's answer 中所述

  1. Check interruption flag in your logic
  2. Act upon Interrupted exception

测试中断标志的例子:

private final class MyTask implements Runnable {

public void run() {
try{
for(int j=0; j<100000000; j++) {
for(int i=1; i<1000000000; i++){
if(Thread.interrupted()){ //Don't use Thread.interrupt()!
Log.debug("Thread was interrupted for" + cache);
return; //Stop doing what you are doing and terminate.
}
Math.asin(0.1565365897770/i);
Math.tan(0.4567894289/i);
}
}
}catch(Throwable e){//if exception is uncaught, the scheduler may not run again
...
}
}
}

据我了解,当应用程序结束运行时,ScheduledExecutorService 可能会shutdown

关于java - 定时器:取消正在运行的任务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9914121/

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