我有一个ScheduledExecutorService
定期执行一些不同的任务scheduleAtFixedRate(Runnable, INIT_DELAY, ACTION_DELAY, TimeUnit.SECONDS);
我也有不一样的Runnable
我正在与这个调度程序一起使用。
当我想从调度程序中删除其中一项任务时,问题就开始了。
有没有办法做到这一点?
我使用一个调度程序来执行不同的任务是否正确?
实现这一点的最佳方法是什么?
只需取消返回的 futurescheduledAtFixedRate()
:
// 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 次并退出。如果该按钮被单击太多次,您可能会得到大量无法被垃圾收集的线程,因为调度程序仍然有引用。
您可能想使用setRemoveOnCancelPolicy(true)
in ScheduledThreadPoolExecutor
Java 7 及以上版本中提供该类。为了向后兼容,默认设置为 false。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)