如何为Executors.newScheduledThreadPool(5)设置RemoveOnCancelPolicy

J. *_* K. 11 java concurrency multithreading

我有这个:

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的任务中结束.

/sf/answers/1009650491/

他们提到了一些事情setRemoveOnCancelPolicy,但是这scheduledThreadPool没有这种方法.我该怎么办?

Ada*_*ker 14

方法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;
}
Run Code Online (Sandbox Code Playgroud)

Executors类通过newScheduledThreadPool和类似方法返回此执行程序.

public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) {
    return new ScheduledThreadPoolExecutor(corePoolSize);
}
Run Code Online (Sandbox Code Playgroud)

简而言之,您可以转换执行程序服务引用来调用该方法

ScheduledThreadPoolExecutor ex = (ScheduledThreadPoolExecutor) Executors.newScheduledThreadPool(5);
ex.setRemoveOnCancelPolicy(true);
Run Code Online (Sandbox Code Playgroud)

或者new ScheduledThreadPoolExecutor自己创造.

ScheduledThreadPoolExecutor ex = new ScheduledThreadPoolExecutor(5);
ex.setRemoveOnCancelPolicy(true);
Run Code Online (Sandbox Code Playgroud)

  • 该死的.我正在开发一个Android应用程序,这个调用`setRemoveOnCancelPolicy`需要API级别21,我的项目支持API方式回到14.还有另一种删除任务的方法吗? (2认同)