I have a while loop in my main Java program method. The loop is supposed to run until the boolean flag variable is set to true in the keyPressed method (I added the program as KeyListener in the JFrame).
import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import javax.swing.JFrame; public class ThreadWhile implements KeyListener { private boolean flag = false; public static void main(String[] args) {
I understand that keyPressed methods execute in their threads, so it seems that when I press a key, the 'flag' variable should be set to true, and the while loop running in the main method should end.
HOWEVER, when I run this program, the loop runs forever, although we can see that the flag variable is correct! Oddly enough, the program behaves correctly if I insert a quick echo message System.out.println of the variable 'flag' inside the while loop, but obviously I don't want to print anything in the loop.
I assume this problem may be the result of a Java compiler trying to optimize an empty while loop until it stops actually checking the 'flag' variable? Does anyone have any suggestions for working correctly on this product, or perhaps even more elegant approaches based on using w390 to pause the main thread until the keyPressed stream being executed is executed?
Thanks!
source share