【问题标题】:How to remove a task from ScheduledExecutorService?如何从 ScheduledExecutorService 中删除任务?
【发布时间】:2013-01-20 10:07:07
【问题描述】:

我有一个 ScheduledExecutorService,它会定期使用 scheduleAtFixedRate(Runnable, INIT_DELAY, ACTION_DELAY, TimeUnit.SECONDS); 执行几个不同的任务

我还有一个不同的Runnable 与此调度程序一起使用。 当我想从调度程序中删除其中一项任务时,问题就开始了。

有没有办法做到这一点?

使用一个调度程序处理不同的任务是否正确? 实现这一点的最佳方法是什么?

【问题讨论】:

    标签: java android scheduledexecutorservice


    【解决方案1】:

    简单地取消scheduledAtFixedRate()返回的future:

    // Create the scheduler
    ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(1);
    // Create the task to execute
    Runnable r = new Runnable() {
        @Override
        public void run() {
            System.out.println("Hello");
        }
    };
    // Schedule the task such that it will be executed every second
    ScheduledFuture<?> scheduledFuture =
        scheduledExecutorService.scheduleAtFixedRate(r, 1L, 1L, TimeUnit.SECONDS);
    // Wait 5 seconds
    Thread.sleep(5000L);
    // Cancel the task
    scheduledFuture.cancel(false);
    

    另外需要注意的是,取消不会从调度程序中删除任务。它只确保isDone 方法总是返回true。如果您继续添加此类任务,这可能会导致内存泄漏。例如:如果您基于某些客户端活动或 UI 按钮单击启动任务,请重复 n 次并退出。如果该按钮被点击太多次,您最终可能会得到大量无法被垃圾收集的线程池,因为调度程序仍然有引用。

    您可能希望在 Java 7 及更高版本中可用的 ScheduledThreadPoolExecutor 类中使用 setRemoveOnCancelPolicy(true)。为了向后兼容,默认设置为 false。

    【讨论】:

    • 使用newSingleThreadScheduledExecutor()的人注意,因为它不会暴露内部执行器:自己创建一个执行器,设置属性,然后用Executors.unconfigurableScheduledExecutorService()包装它。
    • 为什么不能重复使用?为什么取消取消的任务这么难?
    • 要使用setRemoveOnCancelPolicy(true),请在此处查看ScheduledThreadPoolExecutor 的实例化变体说明:stackoverflow.com/a/36748183/3072570
    【解决方案2】:

    如果您的ScheduledExecutorService 实例扩展ThreadPoolExecutor(例如ScheduledThreadPoolExecutor),您可以使用remove(Runnable)(但请参阅其javadoc 中的注释:“它可能无法删除之前已转换为其他形式的任务被放置在内部队列中。”)或purge()

    【讨论】:

    • 感谢解答,当时Executor中没有这个方法
    猜你喜欢
    • 1970-01-01
    • 2012-11-05
    • 2013-11-20
    • 2019-12-14
    • 1970-01-01
    • 1970-01-01
    • 2019-01-30
    • 2022-07-01
    • 1970-01-01
    相关资源
    最近更新 更多