簡體   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