Java中Timer类的schedule方法开始计时时间是不是创建timer对象的时刻

来源:百度知道 编辑:UC知道 时间:2024/06/25 16:35:57
我希望从第一次点击按钮开始就计时,在指定的延时时间后执行某一任务。
举个例子,比如手机输入字母,按一个键是a,再按一次是b,再按一次是c。但是如果到了1秒钟,就输入下一个字符。
另外,如果用schedule方法,我在Timer timer = new Timer();语句后面又写了若干语句,这些语句的执行时间也算在延时时间中吗?
具体语句大概情况如下:
Timer timer = new Timer();
......//一些语句
timer.schedule(new Task(),1000);//程序开始1000毫秒之后执行Task
//请问这里的程序开始是什么时刻?

通过查看JDK源码可以知道如下:
public void schedule(TimerTask task, long delay) {
if (delay < 0)
throw new IllegalArgumentException("Negative delay.");
sched(task, System.currentTimeMillis()+delay, 0);
}
实际上调用的是如下方法:
private void sched(TimerTask task, long time, long period)
//task:安排的任务,the scheduled task;
//time:指定的时间去执行
* at the specified time with the specified period, in milliseconds.
//period:如果period是正数,则会重复执行任务,如果是零则只执行任务一次
If period is
* positive, the task is scheduled for repeated execution;
* zero, the task is scheduled for one-time execution.
因此可以分析到 中间书写的语句不会算在延迟时间中,程序的开始时刻就是执行到timer.schedule(new Task(),1000);//语句时,开始计时。而Timer timer = new Timer() 只是创建了一个Timer类对象。
只有程序执行到timer.schedule(new Task(),1000)时,才会调用
sched(task, System.currentTimeMillis()+delay, 0)方法,而这时该方法
才去执行System.currentTimeMillis取得当前时间,并将该任务加到TaskQueue队列中