gpt4 book ai didi

Java 定时器计数太快

转载 作者:行者123 更新时间:2023-12-01 22:50:27 25 4
gpt4 key购买 nike

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

关于Java 定时器计数太快,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58459527/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com