For this to ever work, some other thread must be setting graphic.m
to true
. So I'll assume that's happening.
My guess is that graphic.m
is not a volatile field. That means that there's no formal happens-before relationship between one thread writing to it (setting it to true
from the other thread) and another thread reading from it (the code you have). The JVM is free to cache values within the thread (or let the CPU cores cache them, etc), and seems to be doing so.
System.out.println
is a synchronized method, though. Even though this doesn't have any formal affect on graphic.m
according to the JLS, it's very possible that the act of releasing/acquiring that synchronization lock would flush memory across cores such that your thread happens to see graphic.m
's latest value. To emphasize: this doesn't have to happen by the Java spec, and you shouldn't rely on that behavior -- if you do, you're likely to be bitten by a hard-to-catch bug in some future version of the JVM, or some slightly different hardware, etc.
The solution would be to make graphic.m
a volatile
field (or get/set it via a synchronized method, or use an AtomicBoolean).