而循环与标志

时间:2013-01-20 21:18:23

标签: java multithreading loops while-loop

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

1 个答案:

答案 0 :(得分: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();
    }
}