繁体   English   中英

如何使用 Java.Util.Timer

[英]How to use Java.Util.Timer

我想制作一个简单的程序,使用 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);

    }

}}

不要使用这个 while 循环:

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

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

而是使用 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();
            }
        }
    };

为了停止计时器,应调用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