是否有一种内置方法可以取消以Runnable
固定速率安排的任务,ScheduledExecutorService.scheduleAtFixedRate
如果在调用取消时它恰好正在运行,则等待它的完成?
考虑以下示例:
public static void main(String[] args) throws InterruptedException, ExecutionException {
Runnable fiveSecondTask = new Runnable() {
@Override
public void run() {
System.out.println("5 second task started");
long finishTime = System.currentTimeMillis() + 5_000;
while (System.currentTimeMillis() < finishTime);
System.out.println("5 second task finished");
}
};
ScheduledExecutorService exec = Executors.newSingleThreadScheduledExecutor();
ScheduledFuture<?> fut = exec.scheduleAtFixedRate(fiveSecondTask, 0, 1, TimeUnit.SECONDS);
Thread.sleep(1_000);
System.out.print("Cancelling task..");
fut.cancel(true);
System.out.println("done");
System.out.println("isCancelled : " + fut.isCancelled());
System.out.println("isDone : " + fut.isDone());
try {
fut.get();
System.out.println("get : didn't throw exception");
}
catch (CancellationException e) {
System.out.println("get : threw exception");
}
}
这个程序的输出是:
5 second task started
Cancelling task..done
isCancelled : true
isDone : true
get : threw exception
5 second task finished
设置一个共享的 volatile 标志似乎是最简单的选择,但如果可能的话,我宁愿避免它。
java.util.concurrent 框架是否内置了此功能?