简体   繁体   English

如何使用 Java.Util.Timer

[英]How to use Java.Util.Timer

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.我想制作一个简单的程序,使用 Java.Util.Timer 计算秒数直到 100 下面的代码是我正在使用的代码,但是它只是一次打印出所有数字,而无需在每个数字之间等待一秒钟。 How would I fix that?我该如何解决? (Ordinarily I would use a thread.sleep but this is just proof of concept.) (通常我会使用 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);

    }

}}

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. while 循环将立即运行,因为它内部没有延迟。 Instead you want to Timer itself to be your loop, meaning there's no need for this loop.相反,您希望 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();
            }
        }
    };

In order to stop the timer the timer.cancel() should be invoked (not only the one of the TimerTask), so the timer is stopped and in cascade the other related threads.为了停止计时器,应调用timer.cancel() (不仅是 TimerTask 之一),因此计时器停止并级联其他相关线程。

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

            }
        }

    };

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

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