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

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

最新更新