简体   繁体   English

Java util Timer无法正常工作

[英]Java util Timer not working correctly

I was wondering if someone might be able to see what I had done wrong here. 我想知道是否有人可以看到我在这里做错了什么。 I am trying to create a timer which will increment the count variable by 1 every second and print it out on the console. 我正在尝试创建一个计时器,该计时器将每秒将count变量增加1并在控制台上将其打印出来。 However, it prints the first number and then stops and I am not sure what is going on. 但是,它将打印第一个数字,然后停止,我不确定发生了什么。

import java.util.Timer;
import java.util.TimerTask;


public class TimerTest  {

    private Timer timer;
    public int count = 0;

    public TimerTest() {
        timer = new Timer();
        timer.schedule(new TimerListener(), 1000);
    }

    private class TimerListener extends TimerTask {

        @Override
        public void run() {
            count++;
            System.out.println(count);
        }

    }

    public static void main(String[] args) {
       new TimerTest();
    }
}

I did find some other questions like this but none of their solutions made any difference to the result. 我确实找到了其他类似的问题,但是他们的解决方案都没有对结果产生任何影响。

Thanks. 谢谢。

Your scheduling only runs the task once. 您的计划仅运行一次任务。 You need to add a parameter to use the method schedule(TimerTask task, long delay, long period) : 您需要添加一个参数以使用方法schedule(TimerTask任务,长时间延迟,长时间)

timer.schedule(new TimerListener(), 1000, 1000);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM