【问题标题】:Button stuck, need to break infinite loop in java按钮卡住,需要在java中打破无限循环
【发布时间】:2013-08-14 18:01:43
【问题描述】:

我正在编写一个程序,它将在给定的时间段内将鼠标移动一定距离。所以我需要算法去:

点击开始

while(true){
    move mouse to point x
    sleep for n seconds
}

这可行,但是当作为线程运行时,仍然按下启动按钮,因为线程一直在运行。因此,我什至无法退出该程序(与任何无限循环一样),并且我无法将布尔值设置为“false”以停止 while 循环。我需要做什么才能使该线程可以在后台运行并且仍然允许我单击停止按钮并使鼠标停止移动?

在我的主要课程中,我有:

public void actionPerformed(ActionEvent e) {

            if (e.getSource() == btnStart) {
                Thread t = new Thread(new Mover(1000, true));
                t.run();
            }
        }

线程类:

import java.awt.AWTException;
import java.awt.MouseInfo;
import java.awt.Robot;

public class Mover implements Runnable {

    int time;
    boolean startStop;

    public Mover(int x, boolean b) {

        time = x;
        startStop = b;

    }

    @Override
    public void run() {

        while (startStop) {
            // TODO Auto-generated method stub

            //Get x position
            int intX = MouseInfo.getPointerInfo().getLocation().x;
            // String intx = Integer.toString(intX);

            //Get y position
            int intY = MouseInfo.getPointerInfo().getLocation().y;

            Robot robot;
            try {
                robot = new Robot();
                robot.mouseMove(intX - 100, intY);
            } catch (AWTException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }

            try {
                Thread.sleep(time);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }// Close while loop
    }

}

【问题讨论】:

  • 您应该始终使用equals(Object) 方法来比较对象,因为使用== 可能会产生意想不到的结果。
  • 使用start() 启动线程,而不是run()

标签: java multithreading infinite-loop runnable


【解决方案1】:

Mover 类中的布尔值创建一个setter:

public void setStartStop(boolean value) {
    startStop = value;
}

然后在您的主类中保留对Mover 的引用。

Mover mover = new Mover(1000, true);
Thread thread = new Thread(mover);
thread.start();
//do stuff
mover.setStartStop(false);

这允许您的外部(即主)线程在运行时影响另一个线程。一旦你启动thread,你的主线程应该会继续正常执行。

【讨论】:

  • 非常感谢。我正在尝试学习线程....并防止我的工作机器自行锁定 ;-)
猜你喜欢
  • 2018-09-01
  • 2013-03-08
  • 2013-05-04
  • 2021-08-29
  • 2012-04-02
  • 1970-01-01
  • 2020-03-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多