[英]How to wait for (fixed rate) ScheduledFuture to complete on cancellation
是否有内置方法取消已通过ScheduledExecutorService.scheduleAtFixedRate
以固定速率安排的Runnable
任务,如果在调用cancel时恰好正在运行,则等待它完成?
请考虑以下示例:
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
设置共享易失性标志似乎是最简单的选择,但我希望尽可能避免使用它。
java.util.concurrent框架是否内置了此功能?
我不完全确定你想要实现什么,但当我从谷歌搜索到这里时,我认为可能值得回答你的问题。
1)如果你想强行停止繁重的工作量 - 不幸的是它似乎没有解决方案(当线程没有响应中断时)。 处理它的唯一方法是在循环中耗时的操作之间插入Thread.sleep(1)( http://docs.oracle.com/javase/1.5.0/docs/guide/misc/threadPrimitiveDeprecation.html ) - 也许deamon线程会有帮助,但我真的不鼓励使用它们。
2)如果你想阻止当前线程直到子线程完成,那么你可以使用get http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/Future.html #get()甚至得到超时。
3)如果你想要清除取消子线程,那么你可以调用:
fut.cancel(false);
这不会中断当前执行,但不会安排它再次运行。
4)如果您的工作负载不重,您只需要等待5秒钟,然后使用线程睡眠或TimeUnit睡眠。 在这种情况下,中断/取消将立即生效。
你的例子缺少对Executor的关闭调用导致应用程序不会停止。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.