如何使用 Java.Util.Timer

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23095690/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 20:40:01  来源:igfitidea点击:

How to use Java.Util.Timer

javatimertimertask

提问by Neil M.

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

我想制作一个简单的程序,使用 Java.Util.Timer 计算秒数直到 100 下面的代码是我正在使用的代码,但是它只是一次打印出所有数字,而无需在每个数字之间等待一秒钟。我该如何解决?(通常我会使用 thread.sleep 但这只是概念证明。)

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);

    }

}}

采纳答案by Hovercraft Full Of Eels

Don't use this while loop:

不要使用这个 while 循环:

    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.

while 循环将立即运行,因为它内部没有延迟。相反,您希望 Timer 本身成为您的循环,这意味着不需要此循环。

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

而是使用 if 块来检查计数是否小于某个最大数字,如果是,则将其打印出来并增加计数。

    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();
            }
        }
    };