【发布时间】: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