开发者

Will a timer keep running indefinetly until its .cancel method has been invoked

Below code starts and runs two timers in order, I would have thought that the first timer would stop running once the second timer is initialised. It seems that when a Timer is given a new reference its previous reference just keeps executing the given task ?

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开发者_StackOverflow社区().runTimer();
    }

    private void runTimer(){
        timer = new Timer();
        timerTask = new TimerTask() {
            public void run() {          
                ++counter;
                System.out.println("output - "+counter);
            }
        };
        timer.scheduleAtFixedRate(timerTask, delay, delay);
    }

}


Yes. Assigning an object reference to a variable doesn't modify the state of the object. The object is, BTW, unable to know if it's assigned to 0, 1 or several variables.

Moreover, note that the second timer is assigned to a different variable than the first one, since you instantiate two TimerTest objects, each having their own timer field.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜