java中timer的schedule和scheduleAtFixedRate方法区别详解
timer的schedule和scheduleAtFixedRate方法一般情况下是没什么区别的,只在某个情况出现时会有区别--当前任务没有来得及完成下次任务又交到手上。
我们来举个例子:
暑假到了老师给schedule和scheduleAtFixedRate两个同学布置作业。
老师要求学生暑假每天写2页,30天后完成作业。
这两个学生每天按时完成作业,直到第10天,出了意外,两个学生出去旅游花了5天时间,这5天时间里两个人都没有做作业。任务被拖延了。
这时候两个学生采取的策略就不同了:
schedule重新安排了任务时间,旅游回来的第一天做第11天的任务,第二天做第12天的任务,最后完成任务花了35天。
scheduleAtFixedRate是个守时的学生,她总想按时完成老师的任务,于是在旅游回来的第一天把之前5天欠下的任务以及第16天当天的任务全部完成了,之后还是按照老师的原安排完成作业,最后完成任务花了30天。
packageday01; importjava.text.SimpleDateFormat; importjava.util.Timer; importjava.util.TimerTask; publicclassTest01{ publicstaticvoidmain(String[]args){ finalTimertimer=newTimer(); //timer.scheduleAtFixedRate(newTimerTask(){ timer.schedule(newTimerTask(){//分别注释这行和上面这行试一试效果 intcount=1; @Override publicvoidrun(){ count++; if(count==10){ try{ Thread.sleep(5000); }catch(InterruptedExceptione){ System.out.println("延迟5s"); e.printStackTrace(); } } SimpleDateFormatsf=newSimpleDateFormat( "yyyyMMddhh:mm:ss"); System.out.println("当前时间:" +sf.format(System.currentTimeMillis())+"计划时间:" +sf.format(scheduledExecutionTime())); } },1000,1000); } }
希望能帮到大家!
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。