亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Java 定時器計數太快

Java 定時器計數太快

繁華開滿天機 2023-11-10 15:25:48
我想寫一個計時器類,每秒計數到0,但似乎計數太快了。我究竟做錯了什么?public class Eieruhr {    private int x;    public Eieruhr (int x){        this.x = x;    }    public static void main(String[] args){        Eieruhr eu = new Eieruhr(10);        eu.start();    }    public void start(){        for(int i = 0; i <= x; x--){            long s = System.nanoTime();            while( ((System.nanoTime() - s) / 100000000) < x);            System.out.println("tick - " + x);        }    }}
查看完整描述

1 回答

?
阿晨1998

TA貢獻2037條經驗 獲得超6個贊

我建議你使用TimeUnit.SECONDS.sleep(1). 看一下代碼:


public class Eieruhr {

    private int x;


    public Eieruhr(int x) {

        this.x = x;

    }


    public static void main(String[] args) throws InterruptedException {

        Eieruhr eu = new Eieruhr(10);

        eu.start();

    }


    public void start() throws InterruptedException {

        for (int i = 0; i < x; i++) {

            TimeUnit.SECONDS.sleep(1);

            System.out.println(new Date() + " tick - " + i);

        }

    }

}

輸出:


Sat Oct 19 15:11:37 EEST 2019 tick - 0

Sat Oct 19 15:11:38 EEST 2019 tick - 1

Sat Oct 19 15:11:39 EEST 2019 tick - 2

Sat Oct 19 15:11:40 EEST 2019 tick - 3

Sat Oct 19 15:11:41 EEST 2019 tick - 4

Sat Oct 19 15:11:42 EEST 2019 tick - 5


查看完整回答
反對 回復 2023-11-10
  • 1 回答
  • 0 關注
  • 145 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號