我有一个嵌套在另一个类中的以下类(它也扩展了线程)
public class Miner extends Thread {
private volatile boolean running = true;
public void setRunning(boolean running) {
this.running = running;
}
public boolean getRunning() {
return running;
}
private void MainLoop() {
if(!running) {
robot.keyRelease(KeyEvent.VK_D);
return;
}
robot.keyPress(KeyEvent.VK_D);
robot.keyRelease(KeyEvent.VK_D);
try {
Thread.sleep(100 + (int)(Math.random()*randInt));
} catch(Exception e) {}
MainLoop();
}
@Override
public void run() {
MainLoop();
}
}
然后在矿工嵌套的课程中
private void MainLoop() throws AWTException {
Miner miner = new Miner();
miner.start();
... does other stuff ...
while(miner.getRunning())
miner.setRunning(false);
... do more stuff ...
MainLoop();
}
但是,在尝试将运行设置为false并停止矿工线程并执行“做更多的事情”之后,我一直在做“做更多的事情”时,仍然要按D键。
包含Miner的类的完整MainLoop()方法。
private void MainLoop() throws AWTException {
if(stop)
return;
Miner miner = new Miner();
miner.start();
while(true) {
BufferedImage screenCap = robot.createScreenCapture(new Rectangle(x, y, 1, 1));
int c = screenCap.getRGB(0,0);
int red = (c & 0x00ff0000) >> 16;
int green = (c & 0x0000ff00) >> 8;
int blue = c & 0x000000ff;
Color color = new Color(red,green,blue);
if(color.equals(DRILL_COLORS[0]) || color.equals(DRILL_COLORS[1]))
break;
try {
Thread.sleep(500);
} catch(Exception e) {}
if(stop)
return;
}
while(miner.getRunning())
miner.setRunning(false);
count++;
if(count >= 3) {
up = !up;
count = 0;
}
switch(moveDir) {
case 0:
if(up)
holdKey(KeyEvent.VK_UP, 100 + (int)(Math.random()*randInt));
else
holdKey(KeyEvent.VK_DOWN, 100 + (int)(Math.random()*randInt));
break;
case 1:
if(up)
holdKey(KeyEvent.VK_RIGHT, 100 + (int)(Math.random()*randInt));
else
holdKey(KeyEvent.VK_LEFT, 100 + (int)(Math.random()*randInt));
break;
}
switch(wallLoc) {
case 0:
holdKey(KeyEvent.VK_UP, 50);
break;
case 1:
holdKey(KeyEvent.VK_DOWN, 50);
break;
case 2:
holdKey(KeyEvent.VK_RIGHT, 50);
break;
case 3:
holdKey(KeyEvent.VK_LEFT, 50);
break;
}
MainLoop();
}
基本上,目标是使Miner线程按下D键,直到它检测到屏幕上某个点上的某种颜色。然后它应该在移动我的角色的同时停止矿工线程,然后重新调用该方法并重新开始。但是矿工线程一直运行。
最佳答案
这里没有stop
概念。
private void MainLoop() throws AWTException {
Miner miner = new Miner();
miner.start();
... does other stuff ...
while(miner.getRunning())
miner.setRunning(false);
... do more stuff ...
MainLoop();
}
最后的方法调用自身=>
MainLoop();
,这是一个递归的无限循环。在这种方法中,创建一个新的
Miner
对象,启动一个新线程,再次按下D
,然后该线程停止,然后再...do more stuff..
,然后整个循环再次开始。