我有一种方法可以启动多个计时器。他们都一个接一个地工作(我只是增加等待每个计时器的时间)。
我需要我的程序等到最后一个计时器完成他的工作!否则我的程序将被无限递归调用。
这是我的方法:
public void doGameLogic(int cellID) {
final ControllerHelper helper = new ControllerHelper();
helper.setIndex(0);
helper.setCellID(cellID);
helper.setDecrement(false);
helper.setFinished(true);
if(actualGameState.getPlayersTurn() == ModelConstants.PLAYER_ONE) {
helper.setActualCoinList(actualGameState.getCoinsPlayerOne());
} else {
helper.setActualCoinList(actualGameState.getCoinsPlayerTwo());
}
if(!(helper.getActualCoinList().get(helper.getCellID()) == 0)) {
if(cellID > ((helper.getActualCoinList().size() / 2) - 1)) {
helper.setIndex(cellID + 1);
} else if(cellID < (helper.getActualCoinList().size() / 2)) {
helper.setIndex(cellID - 1);
}
if(helper.getIndex() < (helper.getActualCoinList().size() / 2)) {
helper.setDecrement(true);
} else if(helper.getIndex() > ((helper.getActualCoinList().size() / 2) - 1)) {
helper.setDecrement(false);
}
int coins = (helper.getActualCoinList().get(cellID));
int time = 500;
for(int i = 0; i < coins; i++) {
Timer timer = new Timer(time, new ActionListener() {
public void actionPerformed(ActionEvent e) {
int tempDec = (helper.getActualCoinList().get(helper.getCellID()) - 1);
helper.getActualCoinList().remove(helper.getCellID());
helper.getActualCoinList().add(helper.getCellID(), tempDec);
if(helper.getIndex() > (helper.getActualCoinList().size() - 1)) {
helper.setIndex(((helper.getActualCoinList().size() / 2) - 1));
helper.setDecrement(true);
} else if(helper.getIndex() < 0) {
helper.setIndex((helper.getActualCoinList().size() / 2));
helper.setDecrement(false);
}
if(!helper.isDecrement()) {
int tempInc = (helper.getActualCoinList().get(helper.getIndex()) + 1);
helper.getActualCoinList().remove(helper.getIndex());
helper.getActualCoinList().add(helper.getIndex(), tempInc);
helper.setIndex(helper.getIndex() + 1);
} else {
int tempInc = (helper.getActualCoinList().get(helper.getIndex()) + 1);
helper.getActualCoinList().remove(helper.getIndex());
helper.getActualCoinList().add(helper.getIndex(), tempInc);
helper.setIndex(helper.getIndex() - 1);
}
setActualGameState(actualGameState);
}
});
timer.setRepeats(false);
timer.start();
time += 1000;
}
if(!helper.isDecrement()) {
helper.setIndex(helper.getIndex() - 1);
} else {
helper.setIndex(helper.getIndex() + 1);
}
if(!(helper.getActualCoinList().get(helper.getIndex()) < 2)) {
doGameLogic(helper.getIndex());
helper.setFinished(false);
}
if(helper.isFinished()) {
if(this.actualGameState.getPlayersTurn() == ModelConstants.PLAYER_ONE) {
this.actualGameState.setPlayersTurn(ModelConstants.PLAYER_TWO);
} else {
this.actualGameState.setPlayersTurn(ModelConstants.PLAYER_ONE);
}
this.gameInfos.getGameHistory().putState(this.actualGameState);
this.setActualGameState(this.actualGameState);
}
} else {
}
}
显然,只要 timer.isRunning() 为真,我就不能让线程等待,因为这只会冻结我的 GUI 或杀死我的程序。
有没有办法让我的程序等待计时器?