Java中用于倒计时的时钟线程

Java中用于倒计时的时钟线程,java,multithreading,thread-safety,sleep,timeunit,Java,Multithreading,Thread Safety,Sleep,Timeunit,我有一个Java问答游戏,每个问题都有一个计数器时间。玩家有10秒时间回答每个问题。为了实现计数器,我创建了一个时钟类,该类使用一个命令类调用bot(游戏实现者类),该命令类发送消息“升级倒计时屏幕”(每个脉冲都可以调用游戏来更新屏幕数据,以使用剩余的新时间,以便玩家可以看到倒计时9、8、7…)。 时钟结束时,发送消息“显示结果并提出新问题” 私有类时钟扩展线程{ CommandMessage endClock=null; CommandMessage pulseClock=null; 僵尸机器

我有一个Java问答游戏,每个问题都有一个计数器时间。玩家有10秒时间回答每个问题。为了实现计数器,我创建了一个时钟类,该类使用一个命令类调用bot(游戏实现者类),该命令类发送消息“升级倒计时屏幕”(每个脉冲都可以调用游戏来更新屏幕数据,以使用剩余的新时间,以便玩家可以看到倒计时9、8、7…)。 时钟结束时,发送消息“显示结果并提出新问题”

私有类时钟扩展线程{
CommandMessage endClock=null;
CommandMessage pulseClock=null;
僵尸机器人;
长秒=10L;
long restSeconds=seconds;//显示还剩多少秒结束计数器。
布尔值isCancelled=false;
@凌驾
公开募捐{
此.setPriority(Thread.MAX_PRIORITY);
试一试{
int i=0;
restSeconds=秒;
//每个脉冲的命令(如可用)(例如,升级屏幕)
而(i
问题:有时,时钟“休眠”的时间太多,远远超过1秒。我可能会被封锁15秒或更长时间。我设置了最大优先级,结果是一样的。此外,当出现大于预期的块时,这是不可预测的

如何确保它只阻塞一秒钟

多谢各位

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