import java.util.Timer; //... Timer timer; //... timer.schedule(new ChangeSomething(),2000);
它将在2秒后执行ChangeSomething(),有没有办法告诉它每2秒钟做一些事情,或者如果我放在ChangeSomething()
timer.schedule(new ChangeSomething(),2000);
它会工作吗
在旁注中,timer.cancel()究竟做了什么?
解决方法
Schedules the specified task for repeated fixed-rate execution,beginning at the specified time. Subsequent executions take place at approximately regular intervals,separated by the specified period.
从用于Timer.cancel()的javadoc:
Terminates this timer,discarding any currently scheduled tasks. Does not interfere with a currently executing task (if it exists). Once a timer has been terminated,its execution thread terminates gracefully,and no more tasks may be scheduled on it.
编辑:
关于执行一个任务一次的Timer的内部执行线程:
After the last live reference to a Timer object goes away and all outstanding tasks have completed execution,the timer’s task execution thread terminates gracefully (and becomes subject to garbage collection). However,this can take arbitrarily long to occur. By default,the task execution thread does not run as a daemon thread,so it is capable of keeping an application from terminating. If a caller wants to terminate a timer’s task execution thread rapidly,the caller should invoke the timer’s cancel method.