线程中定时计划

来源:互联网 发布:sql exists用法 编辑:程序博客网 时间:2024/06/09 18:47

1、scheduleAtFixedRate与scheduleWithFixedDelay的区别

  API文档的描述:
ScheduledFuture<?> scheduleAtFixedRate(Runnable command,
                                       long initialDelay,
                                       long period,
                                       TimeUnit unit)创建并执行一个在给定初始延迟后首次启用的定期操作,后续操作具有给定的周期;也就是将在 initialDelay 后开始执行,然后在 initialDelay+period 后执行,接着在 initialDelay + 2 * period 后执行,依此类推。如果任务的任何一个执行遇到异常,则后续执行都会被取消。否则,只能通过执行程序的取消或终止方法来终止该任务。如果此任务的任何一个执行要花费比其周期更长的时间,则将推迟后续执行,但不会同时执行。 


ScheduledFuture<?> scheduleWithFixedDelay(Runnable command,
                                          long initialDelay,
                                          long delay,
                                          TimeUnit unit)创建并执行一个在给定初始延迟后首次启用的定期操作,随后,在每一次执行终止和下一次执行开始之间都存在给定的延迟。如果任务的任一执行遇到异常,就会取消后续执行。否则,只能通过执行程序的取消或终止方法来终止该任务


感觉描述的还是不是很清晰,其实
第一个方法是固定的频率来执行某项计划,它不受计划执行时间的影响。到时间,它就执行。

而第二个方法,相对固定,是相对任务的。即无论某个任务执行多长时间,等执行完了,我再延迟指定的时间。也就是第二个方法,它受计划执行时间的影响。


final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(5);final Runnable beeper = new Runnable() {int count = 0;public void run() {System.out.println(new Date() + " beep "+ Thread.currentThread().getId());}};final Runnable beeper2 = new Runnable() {int count = 0;public void run() {try {Thread.sleep(4000);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}System.out.println(new Date() + " 休息... "+ +Thread.currentThread().getId());}};// 1秒钟后运行,并每隔2秒运行一次final ScheduledFuture beeperHandle = scheduler.scheduleAtFixedRate(beeper, 1, 2, SECONDS);// 1秒钟后运行,并每隔2秒运行一次 等待5秒后重新运行final ScheduledFuture beeperHandle2 = scheduler.scheduleWithFixedDelay(beeper2, 1, 2, SECONDS);// 30秒后结束关闭任务,并且关闭Schedulerscheduler.schedule(new Runnable() {public void run() {beeperHandle.cancel(true);// beeperHandle2.cancel(true);scheduler.shutdown();}}, 30, SECONDS);





参考:
http://blog.csdn.net/Java2King/article/details/5875819#
http://hi.baidu.com/leige87/item/f4501cd8cdbb693c38f6f74b