使用ScheduledExecutorService尝试TimerTask。安排延迟10秒的任务,并调用task.cancel。但是任务仍在运行,不确定发生了什么,以及取消方法是否似乎没有取消。请帮忙。
package xxx.xxx;
import java.util.TimerTask;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class Tester {
static class OrderWaveTask extends TimerTask{
public void run() {
System.out.println("hi");
}
}
public static void main(String[] args) {
ScheduledExecutorService orderWaveTP = Executors.newScheduledThreadPool(3);
TimerTask task = new Tester.OrderWaveTask();
orderWaveTP.schedule(task, 10, TimeUnit.SECONDS);
System.out.println("cancelling task: "+ task.cancel());
}
}
您应该使用ScheduledFuture取消该任务。将代码更改为以下应该使其工作。
ScheduledFuture<?> future = orderWaveTP.schedule(task, 10, TimeUnit.SECONDS);
System.out.println("cancelling task: "+ future.cancel(false));
TimerTask旨在与Timer类一起使用,以便安排执行和支持取消。
当您通过执行程序安排TimerTask时,您实际上只是告诉执行程序运行Runnable,并且执行程序执行控制;它不知道你正在运行TimerTask,所以TimerTask函数没有任何效果。
您的选择是使用Timer而不是ExecutorService,或使用ExecutorService方法取消执行。