Clock Thread for a countdown in Java

145 Views Asked by At

I have a questions game ready in Java, with a counter time for each question. Players have 10 seconds to answer each question. To implement the counter, I maked a Clock class that calls the bot (the game implementer class) using a command class that sends the message "upgrade the countdown screen" (each pulse can call the game to update screen data with the new time left, so players can see the countdown 9, 8, 7 ...). When clock ends, sends a message "show results and ask new question".

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

The problem: sometimes, clock "sleeps" too much time, much more than 1 second. I can be blocked for 15 seconds or more. I setted maximum priority, and the result is the same. Also, it is unpredictable when a larger than expected block will occur.

How can I make sure that it only blocks for a second?

Thank you.

0

There are 0 best solutions below