我有一个 ScheduledExecutorService
定期使用 scheduleAtFixedRate(Runnable, INIT_DELAY, ACTION_DELAY, TimeUnit.SECONDS);
我还有一个与此调度程序一起使用的不同 Runnable
。
当我想从调度程序中删除其中一项任务时,问题就开始了。
有没有办法做到这一点?
使用一个调度程序处理不同的任务是否正确? 实现这一点的最佳方法是什么?
最佳答案
简单地取消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
。如果您继续添加此类任务,这可能会导致内存泄漏。例如:如果您基于某些客户端 Activity 或 UI 按钮单击启动任务,请重复 n 次并退出。如果该按钮被点击太多次,您最终可能会得到大量无法被垃圾回收的线程池,因为调度程序仍然有引用。
您可能希望在 Java 7 及更高版本中提供的 ScheduledThreadPoolExecutor
类中使用 setRemoveOnCancelPolicy(true)
。为了向后兼容,默认设置为 false。
关于java - 如何从 ScheduledExecutorService 中删除任务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14423449/