the*_*osh 56 java android scheduledexecutorservice
我有一个ScheduledExecutorService
时间周期性的几个不同的任务scheduleAtFixedRate(Runnable, INIT_DELAY, ACTION_DELAY, TimeUnit.SECONDS);
我也有一个Runnable
与此调度程序不同的用法.当我想从调度程序中删除其中一个任务时,问题就开始了.
有没有办法做到这一点?
我是否正确使用一个调度程序执行不同的任务?实现这个的最佳方法是什么?
JB *_*zet 90
只需取消退回的未来scheduledAtFixedRate()
:
// 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);
Run Code Online (Sandbox Code Playgroud)
另一件需要注意的事情是,cancel不会从调度程序中删除任务.它确保的isDone
方法始终是返回true
.如果您继续添加此类任务,这可能会导致内存泄漏.例如:如果您根据某些客户端活动或UI按钮单击启动任务,请重复n次并退出.如果单击该按钮的次数太多,您可能最终会得到大量的线程,这些线程无法进行垃圾回收,因为调度程序仍然具有引用.
您可能需要使用setRemoveOnCancelPolicy(true)
在ScheduledThreadPoolExecutor
Java 7中起可用类.为了向后兼容,default设置为false.
归档时间: |
|
查看次数: |
35588 次 |
最近记录: |