public class Simulation extends Thread {
private volatile boolean loopState = true;
public void stopLoop() {
loopState = false;
}
public void run() {
try {
Robot r = new Robot();
while (loopState) {
r.keyPress(KeyEvent.VK_LEFT);
r.keyRelease(KeyEvent.VK_LEFT);
sleep(50);
}
} catch (AWTException | InterruptedException e) {}
}
}
When I launch stopLoop() the while loop below doesn’t stop. If I print the value of loopState at the end of the stopLoop() call it returns false but the loop is still executing.
I use this code to call the methods.
Simulation simulation = new Simulation();
switch (PressedButtonID) {
case 14:
simulation.start();
break;
case 15:
simulation.stopLoop();
break;
}
Your posted code works perfectly, as the following simple program demonstrates: as you can see, the while loop stops as expected. The problem is somewhere else.