Java 定时器计数太快

我想写一个计时器类,每秒计数到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);


        }

    }

}


繁华开满天机
浏览 59回答 1
1回答

阿晨1998

我建议你使用TimeUnit.SECONDS.sleep(1). 看一下代码:public class Eieruhr {&nbsp; &nbsp; private int x;&nbsp; &nbsp; public Eieruhr(int x) {&nbsp; &nbsp; &nbsp; &nbsp; this.x = x;&nbsp; &nbsp; }&nbsp; &nbsp; public static void main(String[] args) throws InterruptedException {&nbsp; &nbsp; &nbsp; &nbsp; Eieruhr eu = new Eieruhr(10);&nbsp; &nbsp; &nbsp; &nbsp; eu.start();&nbsp; &nbsp; }&nbsp; &nbsp; public void start() throws InterruptedException {&nbsp; &nbsp; &nbsp; &nbsp; for (int i = 0; i < x; i++) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; TimeUnit.SECONDS.sleep(1);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.println(new Date() + " tick - " + i);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}输出:Sat Oct 19 15:11:37 EEST 2019 tick - 0Sat Oct 19 15:11:38 EEST 2019 tick - 1Sat Oct 19 15:11:39 EEST 2019 tick - 2Sat Oct 19 15:11:40 EEST 2019 tick - 3Sat Oct 19 15:11:41 EEST 2019 tick - 4Sat Oct 19 15:11:42 EEST 2019 tick - 5
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java