如何使用 Java.Util.Timer [英] How to use Java.Util.Timer

查看:32
本文介绍了如何使用 Java.Util.Timer的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

    }

}}

推荐答案

不要使用这个 while 循环:

Don't use this while loop:

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

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

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.

改为使用 if 块来检查计数是否小于等于

一些最大数量,如果是,打印出来并增加计数.

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

这篇关于如何使用 Java.Util.Timer的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆