为了账号安全,请及时绑定邮箱和手机立即绑定

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 关注
  • 53 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信