And*_*rey 7 java concurrency timer executorservice executor
我有这个问题:
我有一个计时器.使用scheduleAtFixedRate,它会创建一个新的Timer任务.在该计时器任务中有某些代码,可能需要一段时间才能完成.如何在前一个任务尚未完成时确保Timer不会创建新任务?
谢谢
ska*_*man 18
我的答案是不使用Timer,它已经过时了.自Java5以来,Timer已经被取代了ScheduledExecutorService,它更灵活,更易于使用.您可以更好地控制调度程序的工作方式,即您无法获得的控制类型Timer.
您可以使用Executors工厂类创建一个工厂类,该工厂类具有许多工厂方法.您应该关注的是newSingleThreadScheduledExecutor,它应该完全符合您的要求:
创建一个单线程执行程序,可以调度命令在给定的延迟后运行,或者定期执行.保证任务按顺序执行,并且在任何给定时间不会有多个任务处于活动状态.
使用a ScheduledExecutorService而不是子类TimerTask,Runnable直接进行子类化,然后将任务提交给执行程序.执行程序有各种方法,你需要选择哪一种方法适合你的需要(ScheduledExecutorService仔细阅读javadoc ),但要点是这样的:
// initialise the executor
ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
while (tasksRemaining) {
// create your task
Runnable task = ....;
// submit it to the executor, using one of the various scheduleXYZ methods
executor.schedule(task, delay, unit);
}
// when everything is finished, shutdown the executor
executor.shutdown();
Run Code Online (Sandbox Code Playgroud)
像往常一样,阅读javadoc.