1
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;
}
4

1 回答 1

0

您发布的代码完美运行,如以下简单程序所示:如您所见,while 循环按预期停止。问题出在其他地方。

import java.awt.*;
import java.awt.event.KeyEvent;

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);
                System.out.println("Simulation loop: CALLED");
                sleep(50);
            }
        } catch (AWTException | InterruptedException e) {}
    }

    public static void main(String[] args) throws InterruptedException {
        Simulation simulation = new Simulation();
        simulation.start();
        Thread.sleep(1000);
        simulation.stopLoop();
    }
}
于 2013-01-20T22:05:36.720 回答