且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何从ScheduledExecutorService的任务?

更新时间:2023-01-12 18:26:37

干脆取消由 scheduledAtFixedRate回到未来()

public static void main(String[] args) throws InterruptedException {
    ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(1);
    Runnable r = new Runnable() {
        @Override
        public void run() {
            System.out.println("Hello");
        }
    };
    ScheduledFuture<?> scheduledFuture =
        scheduledExecutorService.scheduleAtFixedRate(r, 1L, 1L, TimeUnit.SECONDS);
    Thread.sleep(5000L);
    scheduledFuture.cancel(false);
}

另外要注意的是,取消不会从调度删除该任务。它所保证的是,isDone方法总是返回true。这可能会导致内存泄漏,如果你继续增加这样的任务。对于例如:如果你开始基于一些客户活动或UI按钮,单击任务,重复n次,然后退出。如果该按钮被点击的次数太多,你可能最终与线程不能被垃圾收集调度仍有引用大水池。

Another thing to note is that cancel does not remove the task from scheduler. All it ensures is that isDone method always return true. This may lead to memory leaks if you keep adding such tasks. For e.g.: if you start a task based on some client activity or UI button click, repeat it n-times and exit. If that button is clicked too many times, you might end up with big pool of threads that cannot be garbage collected as scheduler still has a reference.

您可能需要使用setRemoveOnCancelPolicy(真)在Java 7中起可用的ScheduledThreadPoolExecutor类。为了向后兼容,默认设置为false。

You may want to use setRemoveOnCancelPolicy(true) in ScheduledThreadPoolExecutor class available in Java 7 onwards. For backward compatibility, default is set to false.