I'm currently running a separate task in a Java Swingworker
, and here is the code (edited for clarity):
while (true) {
while (value == 0) {
value = utils.getValue();
System.out.println("Value is zero");
}
System.out.println("Value isn't zero, out of loop");
}
This code runs perfectly fine. However, if I remove the println("Value is zero"), nothing happens, and the loop is never exited. Another thread is handling the population of the value, which gets updated roughly 5 seconds after the program starting.
I'm a little confused as to why the code only executes if there is a println in there. Can anyone shine any light on this?
My best guess: add some sleep condition to give the other thread time to populate the result. In your question you say it takes about 5 seconds; this might take (way) longer when you add a busy-wait loop (while true).
try:
while (true) {
while (value == 0) {
value = utils.getValue();
try {
Thread.sleep(500);
}
catch (InterruptedException e) {
}
System.out.println("Value is zero");
}
System.out.println("Value isn't zero, out of loop");
}