Java倒计时的时钟线程

时间:2020-03-24 12:00:36

标签: java multithreading thread-safety sleep timeunit

我有一个用Java准备的问题游戏,每个问题都有对应的时间。玩家有10秒的时间回答每个问题。为了实现计数器,我制作了一个Clock类,该类使用一个命令类来调用机器人(游戏实现者类),该命令类发送消息“ upgrade the countdown screen”(每个脉冲都可以调用游戏以用剩余的新时间更新屏幕数据) ,因此玩家可以看到倒数9、8、7 ...)。 时钟结束后,发送一条消息“显示结果并提出新问题”。

private class Clock extends Thread {

    CommandMessage endClock = null;
    CommandMessage pulseClock = null;
    BotTrivial bot;
    long seconds = 10L;
    long restSeconds = seconds; //To show how many seconds left to end the counter.
    boolean isCancelled = false;

    @Override
    public void run() {
        this.setPriority(Thread.MAX_PRIORITY);
        try {
            int i = 0;
            restSeconds = seconds;
            //Command for each pulse if available (for example, upgrade screen)
            while (i < seconds && !this.isCancelled) {
                if (this.pulseClock != null && !this.isCancelled) {
                    this.bot.executeCommand(pulseClock);
                }
                TimeUnit.SECONDS.sleep(1);
                i++;
                restSeconds--;
                if (this.isCancelled) {
                    isCancelled = false;
                    return;
                }
            }
            //Command to end if available.
            if (endClock != null && !this.isCancelled) {
                this.bot.executeCommand(endClock);
            }
            isCancelled = false;
        } catch (InterruptedException excp) {
            ErrorRegister.addErrorLogAndCommand("Error: " + excp);
        }
    }

    public void cancel() {
        this.isCancelled = true;
    }

    public long getRestSeconds() {
        return this.restSeconds;
    }
}

问题:有时,时钟“睡眠”的时间过多,超过1秒。我可能会被封锁15秒或更长时间。我设置了最大优先级,结果是一样的。另外,无法预测何时会出现大于预期的块。

我如何确保它仅阻塞一秒钟?

谢谢。

0 个答案:

没有答案
相关问题