ScheduledThreadPoolExecutor

ScheduledThreadPoolExecutor

我有这个:

ScheduledExecutorService scheduledThreadPool = Executors
        .newScheduledThreadPool(5);

然后,我开始一个这样的任务:
scheduledThreadPool.scheduleAtFixedRate(runnable, 0, seconds, TimeUnit.SECONDS);

我通过以下方式保留对Future的引用:
ScheduledFuture<?> scheduledFuture = scheduledThreadPool.scheduleAtFixedRate(runnable, 0, seconds, TimeUnit.SECONDS);

我希望将来可以取消并删除
scheduledFuture.cancel(true);

但是,此SO答案指出,取消操作不会将其删除,而添加新任务将导致许多无法使用GC的任务结束。

https://stackoverflow.com/a/14423578/2576903

他们提到了有关setRemoveOnCancelPolicy的内容,但是此scheduledThreadPool没有这种方法。我该怎么办?

最佳答案

methodScheduledThreadPoolExecutor中声明。

/**
 * 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;
}

该执行程序由exect类通过newScheduledThreadPool和类似方法返回。
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);

10-07 23:36