Java Timer计数太快

时间:2019-10-19 00:25:16

标签: java timer

我想编写一个计时器类,该类每秒计数一次直到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 个答案:

答案 0 :(得分:0)

我建议您使用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