我有这个:
ScheduledExecutorService scheduledThreadPool = Executors .newScheduledThreadPool(5);
然后,我开始执行如下任务:
scheduledThreadPool.scheduleAtFixedRate(runnable, 0, seconds, TimeUnit.SECONDS);
我这样保存对未来的引用:
ScheduledFuture<?> scheduledFuture = scheduledThreadPool.scheduleAtFixedRate(runnable, 0, seconds, TimeUnit.SECONDS);
我希望能够取消 和删除 未来
scheduledFuture.cancel(true);
但是,此SO答案指出,取消操作不会将其删除,而添加新任务将以许多无法使用GC的任务结束。
http://codingdict.com/questions/155838
他们提到了有关的内容setRemoveOnCancelPolicy,但是这种scheduledThreadPool方法没有。我该怎么办?
setRemoveOnCancelPolicy
scheduledThreadPool
此方法在ScheduledThreadPoolExecutor中声明。
/** * Sets the policy on whether cancelled tasks should be immediately * removed from the work queue at time of cancellation. This value is * by default {@code false}. * * @param value if {@code true}, remove on cancellation, else don't * @see #getRemoveOnCancelPolicy * @since 1.7 */ public void setRemoveOnCancelPolicy(boolean value) { removeOnCancel = value; }
Executors类通过newScheduledThreadPool和类似方法返回此执行程序。
public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) { return new ScheduledThreadPoolExecutor(corePoolSize); }
简而言之,您可以强制转换执行程序服务引用以调用该方法
ScheduledThreadPoolExecutor ex = (ScheduledThreadPoolExecutor) Executors.newScheduledThreadPool(5); ex.setRemoveOnCancelPolicy(true);
或new ScheduledThreadPoolExecutor自己创建。
new ScheduledThreadPoolExecutor
ScheduledThreadPoolExecutor ex = new ScheduledThreadPoolExecutor(5); ex.setRemoveOnCancelPolicy(true);