我有这个:
ScheduledExecutorService scheduledThreadPool = Executors
.newScheduledThreadPool(5);
然后我开始这样的任务:
scheduledThreadPool.scheduleAtFixedRate(runnable, 0, seconds, TimeUnit.SECONDS);
我以这种方式保留对 Future 的引用:
ScheduledFuture<?> scheduledFuture = scheduledThreadPool.scheduleAtFixedRate(runnable, 0, seconds, TimeUnit.SECONDS);
我希望能够取消并删除 future
scheduledFuture.cancel(true);
然而,这个 SO 回答指出,取消并不会删除它,添加新任务将导致许多无法进行 GC 的任务。
https://stackoverflow.com/a/14423578/2576903
他们提到了一些关于 setRemoveOnCancelPolicy
的东西,但是这个 scheduledThreadPool
没有这样的方法。我该怎么办?
最佳答案
这method在 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;
}
此执行器由 newScheduledThreadPool 的 Executors 类返回和类似的方法。
public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) {
return new ScheduledThreadPoolExecutor(corePoolSize);
}
所以简而言之,您可以转换执行程序服务引用来调用方法
ScheduledThreadPoolExecutor ex = (ScheduledThreadPoolExecutor) Executors.newScheduledThreadPool(5);
ex.setRemoveOnCancelPolicy(true);
或者自己创建new ScheduledThreadPoolExecutor
。
ScheduledThreadPoolExecutor ex = new ScheduledThreadPoolExecutor(5);
ex.setRemoveOnCancelPolicy(true);
关于java - 如何为Executors.newScheduledThreadPool设置RemoveOnCancelPolicy(5),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36747987/