How to use Java.Util.Timer

无人久伴 提交于 2019-12-23 17:32:34

问题


I want to make a simple program that counts seconds up until 100 using Java.Util.Timer The code below is the code I am using, however it simply prints all the numbers out at once without waiting a second between each one. How would I fix that? (Ordinarily I would use a thread.sleep but this is just proof of concept.)

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

public class Main {
    static Timer timer = new Timer();
    static int seconds = 0;

    public static void main(String[] agrs) {

        MyTimer();

    }

    public static void MyTimer() {

        TimerTask task;

        task = new TimerTask() {
            @Override
            public void run() { 
                while (seconds < 100) {
                    System.out.println("Seconds = " + seconds);
                    seconds++;
                }
            }
        };
         timer.schedule(task, 0, 1000);

    }

}}

回答1:


Don't use this while loop:

    task = new TimerTask() {
        @Override
        public void run() { 
            while (seconds < 100) {
                System.out.println("Seconds = " + seconds);
                seconds++;
            }
        }
    };

The while loop will run immediately as there's no delay inside of it. Instead you want to Timer itself to be your loop, meaning there's no need for this loop.

Instead use an if block to check if the count is < some max number and if so, print it out and increment the count.

    task = new TimerTask() {
        private final int MAX_SECONDS = 100;

        @Override
        public void run() { 
            if (seconds < MAX_SECONDS) {
                System.out.println("Seconds = " + seconds);
                seconds++;
            } else {
                // stop the timer
                cancel();
            }
        }
    };


来源:https://stackoverflow.com/questions/23095690/how-to-use-java-util-timer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!