Here is a snippet of the code I think does not follow what code should do:
public void updateTimeElapsed() {
timeElapsedLabel.setText("Time elapsed: " + ((System.nanoTime() - time) / Math.pow(10, 9)));
}
public void updateTimeElapsedIndefinitely() {
while (true) {
//System.out.println("Hi");
//TODO: Why this no work?
if (start) { System.out.println("Shoulda'"); updateTimeElapsed(); }
}
}
If I comment
System.out.println("Hi")
The code apparently does not work.
If I uncomment it, then it does!
Note:
start is true as soon as you press ‘s’ to start the game.
However, the method is called in the beginning so “hi” should be displayed many times and indefinitely until I press the ‘s’ key.
A picture says a thousand words, so I’ll give you hundreds of pictures (video) to explain what I mean:
https://dl.dropbox.com/u/2792692/CodeWeird.ogv
https://dl.dropbox.com/u/2792692/CodeWeird.wmv
Can anyone tell me what is going on?
Looks like the boolean
startis being updated by another thread but you didn’t declare it asvolatile, so the loop never looks at the updated value.“Fixing” it by adding the println is just a wierd consequence of the way JVM manages the thread’s stack state when it goes to acquire the native system object for the console printer. The fix is to make start volatile and/or synchronize around accessing it.
SCCE:
Never prints:
Starts spamming Hello after 1 second by changing to this:
private volatile boolean start = false;