在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.

相关文章

ArrayList简介:ArrayList 的底层是数组队列,相当于动态数组。与 Java 中的数组相比,它的容量能动态增...
一、进程与线程 进程:是代码在数据集合上的一次运行活动,是系统进行资源分配和调度的基本单位。 线程...
本文为博客园作者所写: 一寸HUI,个人博客地址:https://www.cnblogs.com/zsql/ 简单的一个类...
#############java面向对象详解#############1、面向对象基本概念2、类与对象3、类和对象的定义格式4、...
一、什么是异常? 异常就是有异于常态,和正常情况不一样,有错误出错。在java中,阻止当前方法或作用域...
Collection接口 Collection接口 Collection接口 Collection是最基本的集合接口,一个Collection代表一组...