栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何从ScheduledExecutorService中删除任务?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何从ScheduledExecutorService中删除任务?

只需取消以下项返回的未来

scheduledAtFixedRate()

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

要注意的另一件事是,取消不会从计划程序中删除任务。它所确保的是isDone方法总是返回true。如果继续添加此类任务,可能会导致内存泄漏。例如:如果您基于某个客户端活动或单击UI按钮来启动任务,请重复n次并退出。如果该按钮被单击了太多次,则可能会导致无法进行垃圾回收的线程池很大,因为调度程序仍具有引用。

您可能要在Java 7及更高版本中使用

setRemoveonCancelPolicy(true)
ScheduledThreadPoolExecutor
类中使用。为了向后兼容,默认设置为false。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/404448.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号