下面的代码按顺序启动并运行两个计时器,我本以为一旦第二个计时器初始化,第一个计时器就会停止运行。似乎当一个计时器被给予一个新的引用时,它之前的引用只是继续执行给定的任务?
public class TimerTest {
private TimerTask timerTask;
private Timer timer;
private int counter = 0;
private final int delay = 1000;
public static void main(String[] args){
new TimerTest().runTimer();
new TimerTest().runTimer();
}
private void runTimer(){
timer = new Timer();
timerTask = new TimerTask() {
public void run() {
++counter;
System.out.println("output - "+counter);
}
};
timer.scheduleAtFixedRate(timerTask, delay, delay);
}
}
最佳答案
是的。将对象引用分配给变量不会修改对象的状态。顺便说一句,该对象无法知道它是否被分配给 0、1 或者多个变量。
此外,请注意,第二个计时器被分配给与第一个计时器不同的变量,因为您实例化了两个 TimerTest 对象,每个对象都有自己的计时器字段。
关于java - 计时器是否会无限期地继续运行,直到调用其 .cancel 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7268840/