[英]Java - Thread Doesn't Stop
我有一個嵌套在另一個類中的以下類(它也擴展了線程)
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..
然后整個循環再次開始。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.