Skip to content
Advertisement

Clock thread in Java

I have been studying about Java Thread recently. I created this simple clock that will display how many seconds have passed. It looked like this
frame

Here is the code for the application above (including 2 classes: Main and ClockPanel)

JavaScript
JavaScript

The problem is: if i remove the line System.out.println() (as i commented in the code above), the clock will not run. I have no idea why this is happening at all. Can someone explain it to me? Is it because System.out.println() affect running thread or something?

Advertisement

Answer

isRunning is not volatile and therefore the value each thread sees can diverge. You have a loop that just spins when the value is false and has no reason to go and check to see if the “real” value has change.

Note, you shouldn’t use Swing components (directly or indirectly) off of the AWT Event Dispatch Thread (EDT).

The simple fix is to make isRunning volatile and use EventQueue.invokeLater to invoke timeValue.setText.

Better would be to completely replace clockThread with a javax.swing.Timer (not java.util.Timer!), but that might be missing the point. At least make clockThread wait for isRunning to change.

Advertisement