我有这个:
ScheduledExecutorService scheduledThreadPool = Executors
.newScheduledThreadPool(5);
Run Code Online (Sandbox Code Playgroud)
然后我开始这样的任务:
scheduledThreadPool.scheduleAtFixedRate(runnable, 0, seconds, TimeUnit.SECONDS);
Run Code Online (Sandbox Code Playgroud)
我以这种方式保留对Future的引用:
ScheduledFuture<?> scheduledFuture = scheduledThreadPool.scheduleAtFixedRate(runnable, 0, seconds, TimeUnit.SECONDS);
Run Code Online (Sandbox Code Playgroud)
我希望能够取消并删除未来
scheduledFuture.cancel(true);
Run Code Online (Sandbox Code Playgroud)
然而,这个SO答案指出,取消不会删除它,并且添加新任务将在许多无法进行GC的任务中结束.
他们提到了一些事情setRemoveOnCancelPolicy,但是这scheduledThreadPool没有这种方法.我该怎么办?
是否有一种内置方法可以取消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"); …Run Code Online (Sandbox Code Playgroud)