如果在遍历一个List的时候向其中添加新元素,java就会抛出ConcurrentModificationException异常。
但是我们需要这个功能。在游戏引擎中非常需要这个功能。例如很多BOSS过了一段时间后身上追加了一件神器,
或者很多飞机设计游戏,航空母舰 增加一台小飞机。
java.util.ConcurrentModificationException BUG产生的原因
解决思路是Actor添加元素,并不会立刻添加进List中
而是等Actor在重新绘制追加新元素
代码示例
public class Actor implements IAct {
/** 延迟追加列表 */
protected LinkedList<IAct> addList;
/** 延迟移除列表 */
protected LinkedList<IAct> removeList;
/**
* 给扮演者添加一个扮演者
* 这个方法不会立刻执行而是在
* 这个方法上draw方法前调用
* @see #safeIterator()
* @see #draw(GameCanvas, IAct)
*/
public void addAct(IAct act) {
if (act == this) {
return;
}
if (addList == null) {
addList = new LinkedList
();
}
Log.e("tag", "" + addList.size());
System.out.println("=====" + addList);
addList.add(act);
}
/**
* 给扮演者添加一个扮演者
* 这个方法直接运行会不安全
* 产生java.util.ConcurrentModificationException
* 这个方法上draw方法前调用
* @see #safeIterator()
* @see #draw(GameCanvas, IAct)
*/
private void addActOfTrue(IAct act) {
if (childList == null) {
childList = new ArrayList
();
}
// 如果act的容器父类已经存在
if (act.getActParent() != null) {
// 将它的从它的容器中移除
act.getActParent().removeAct(act);
}
childList.add(act);
act.setGameStage(getGameStage());
act.setActParent(this);
}
/**
* 给扮演者一次一个扮演者
* 这个方法直接运行会不安全
* 产生java.util.ConcurrentModificationException
* 这个方法上draw方法前调用
* @see #safeIterator()
* @see #draw(GameCanvas, IAct)
*/
private void removeActOfTrue(IAct act) {
if (act == this) {
return;
}
// 添加新元素时可能会造成
if (childList == null) {
return;
} else {
// 如果act的容器父类已经存在
if (act.getActParent() != null) {
// 将它的从它的容器中移除
act.getActParent().removeAct(act);
}
}
childList.remove(act);
act.setActParent(null);
}
/**
* 给扮演者移除一个扮演者
* 这个方法不会立刻执行而是在
* 这个方法上draw方法前调用
* @see #safeIterator()
* @see #draw(GameCanvas, IAct)
*/
public void removeAct(IAct act) {
if (removeList == null) {
removeList = new LinkedList
();
}
removeList.add(act);
}
/***
* 安全迭代
* 该方法在draw方法前调用
* @see Actor#draw(GameCanvas, IAct);
*/
protected final void safeIterator()
{
if (addList != null) {
while (!addList.isEmpty()) {
this.addActOfTrue(addList.poll());
}
addList = null;
}
if (removeList != null) {
while (!removeList.isEmpty()) {
this.removeActOfTrue(removeList.poll());
}
removeList = null;
}
}
/** 绘制当前 */
public void draw(GameCanvas canvas, IAct thisAct) {
//绘制前将需要添加的扮演导入
safeIterator();
// 绘制当前造型
if (getModel() != null)
getModel().drawPlay(canvas, thisAct);
// 绘制子扮演者
drawChild(canvas);
if (this.getScript() != null) {
this.getScript().callTimeScript(thisAct.getGameStage(), canvas,
this);
}
};
/** 绘制子扮演者 */
public void drawChild(GameCanvas canvas) {
if (childList != null) {
Iterator
it = childList.iterator();
while (it.hasNext()) {
IAct act = it.next();
act.draw(canvas, act);
}
}
}