内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用
这两种方法的区别是什么?Timer
班级:
schedule(TimerTask task, long delay, long period)
和
scheduleAtFixedRate(TimerTask task, long delay, long period)
已经为一些想要练习和学习的人写了一个示例代码。
import java.util.Timer; import java.util.TimerTask; public class TimerTest { public static void main(String args[]){ TimerTest.DelayTask task = new DelayTask(); Timer timer = new Timer(); /** * Use schedule or scheduletAtFixedrate and check the printed result */ timer.schedule(task, 0, 5000); //timer.scheduleAtFixedRate(task, 0, 5000); } public static boolean stop = false; public static void delayOneSec(String status){ try{ System.out.print(status); Thread.sleep(1000); }catch(Exception e){ e.printStackTrace(); } } static class DelayTask extends TimerTask{ int count = 2; @Override public void run() { // TODO Auto-generated method stub stop = true; for(int i = 0; i < count; i++){ TimerTest.delayOneSec("T"); } if(count == 2){ count = 6; }else{ count = 2; } stop = false; new PrintW().start(); } } static class PrintW extends Thread{ @Override public void run(){ while(!stop){ TimerTest.delayOneSec("W"); } } } }
源代码Timer
public void schedule(TimerTask task, Date firstTime, long period) { if (period <= 0) throw new IllegalArgumentException("Non-positive period."); sched(task, firstTime.getTime(), -period); } public void scheduleAtFixedRate(TimerTask task, long delay, long period) { if (delay < 0) throw new IllegalArgumentException("Negative delay."); if (period <= 0) throw new IllegalArgumentException("Non-positive period."); sched(task, System.currentTimeMillis()+delay, period); }
下面的代码位于mainloop
成TimerThread
,,,
currentTime = System.currentTimeMillis(); executionTime = task.nextExecutionTime; if (taskFired = (executionTime<=currentTime)) { if (task.period == 0) { // Non-repeating, remove queue.removeMin(); task.state = TimerTask.EXECUTED; } else { // Repeating task, reschedule queue.rescheduleMin( task.period<0 ? currentTime - task.period : executionTime + task.period); } } }