如何为Executors.newScheduledThreadPool(5)

时间:2016-04-20 15:08:02

标签: java multithreading concurrency

我有这个:

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操作的任务中结束。

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

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

1 个答案:

答案 0 :(得分:12)

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

Executors类通过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);