I'm having a pretty weird problem with a java thread busy-waiting.
I have one thread that busy waits on the state of a static variable of some other thread. Let's say the thread that busy waits is waiting for another thread's static int variable to reach a certain value
while(OtherThread.countInt < 5);
If I use the above code, the thread will be stuck busy-waiting and will not break out of the while loop, even if static int countInt
does reach 5.
while(OtherThread.countInt < 5) {
// waste some time doing meaningless work
}
If I use this other code, however, then the thread does break out of the busy-wait loop. Sometimes, as soon as countInt
reaches 5, other times a little while after. But it happens. For my particular example, I used this as the "meaningless work"
print("busy waiting...",1000) // wasting time doing meaningless work
where I defined print
as synchronzied static void print(String s, int n)
that prints string s
and then sleeps for n
milliseconds.
What gives? Why does the thread get stuck busy waiting on the first code, but not on the other? All threads have same priorities, so it can't be a priority issue.