I posted not too long ago with code for a timer (that counts to 25s) which was broken, I fixed the issues, but now the JVM reports it taking longer (1 second longer) than it should run for, although the code prints out the time taken, which reports that it works fine, here’s the code:
public static void main(String[] args) {
Runnable ticker = new Timer();
Thread t = new Thread(ticker);
t.start();
}
}
class Timer implements Runnable {
long oneClock;
long twoClock;
int gameLength = 26; //+1 of required time (zeroth degree)
long diff;
long beforeTime;
long afterTime;
long realTime;
boolean loop = false;
public void run () {
beforeTime = System.nanoTime()/1000000000;
while (gameLength > 0){
oneClock = System.nanoTime()/1000000000;
loop = true;
while (loop) {
try {
Thread.sleep(10); } catch (InterruptedException ex) {ex.printStackTrace(); }
twoClock = System.nanoTime()/1000000000;
diff = twoClock - oneClock;
if (diff >= 1) {
gameLength -= diff;
System.out.println (this.gameLength) ;
loop = false;
} //second while close
}
} // 1st while close
afterTime = System.nanoTime()/1000000000;
realTime = afterTime - beforeTime;
System.out.println("The end of the clock");
System.out.println("The clock took" + realTime + "seconds to finish");
}
}
the result is:
run:
25
24
23
22
21
20
19
18
17
16
15
14
13
12
11
10
9
8
7
6
5
4
3
2
1
0
The end of the clock
The clock took26seconds to finish
BUILD SUCCESSFUL (total time: 26 seconds)
if you can point out the obvious mistake I’ll give you a virtual sticker, especially because it’s not obvious to me