在Java中创建重复的定时器提醒

前端之家收集整理的这篇文章主要介绍了在Java中创建重复的定时器提醒前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想要一个类,每2秒更改自己的私有变量.我知道如果我做某事
import java.util.Timer;
//...
Timer timer;
//...
timer.schedule(new ChangeSomething(),2000);

它将在2秒后执行ChangeSomething(),有没有办法告诉它每2秒钟做一些事情,或者如果我放在ChangeSomething()

timer.schedule(new ChangeSomething(),2000);

它会工作吗

在旁注中,timer.cancel()究竟做了什么?

解决方法

使用timer.scheduleAtFixedRate()来安排它每两秒重复一次:

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.

原文链接:https://www.f2er.com/java/125706.html

猜你在找的Java相关文章