How to setRemoveOnCancelPolicy for Executors.newScheduledThreadPool(5)

前端 未结 1 527
天命终不由人
天命终不由人 2021-01-17 13:12

I have this:

ScheduledExecutorService scheduledThreadPool = Executors
        .newScheduledThreadPool(5);

Then I start a task like so:

相关标签:
1条回答
  • 2021-01-17 13:41

    This method is declared in 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;
    }
    

    This executor is returned by Executors class by newScheduledThreadPool and similar methods.

    public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) {
        return new ScheduledThreadPoolExecutor(corePoolSize);
    }
    

    So in short, you can cast the executor service reference to call the method

    ScheduledThreadPoolExecutor ex = (ScheduledThreadPoolExecutor) Executors.newScheduledThreadPool(5);
    ex.setRemoveOnCancelPolicy(true);
    

    or create new ScheduledThreadPoolExecutor by yourself.

    ScheduledThreadPoolExecutor ex = new ScheduledThreadPoolExecutor(5);
    ex.setRemoveOnCancelPolicy(true);
    
    0 讨论(0)
提交回复
热议问题