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) {}
}
}
当我启动下面stopLoop()
的while
循环时不会停止。loopState
如果我在调用结束时打印它的值,stopLoop()
它会返回false
,但循环仍在执行。
我使用此代码来调用方法。
Simulation simulation = new Simulation();
switch (PressedButtonID) {
case 14:
simulation.start();
break;
case 15:
simulation.stopLoop();
break;
}