如何创建秒计时器



我希望我的int time = 0每秒增加 1 次,并具有暂停和恢复的能力。

对于计时器,从这里开始,java计时器教程给它一个破解,并在遇到困难时问另一个问题。

final AtomicLong i = new AtomicLong(0);
Thread th = new Thread() {
    @Override
    public void run() {
        try {
            while (true) {
                long lastSeconds = System.currentTimeMillis() / 1000;
                sleep(100);
                long delta = System.currentTimeMillis() / 1000 - lastSeconds;
                i.getAndAdd(delta);
                if (delta > 0)
                    System.out.println(i.get());
            }
        }
        catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
};
th.start();

最新更新