2015-03-08 74 views
0

我正在製作一個射擊遊戲,作爲敵人在演員中隨機射擊的項目。但每當敵人隨機射擊時,就會拋出java.util.ConcurrentModificationException。 這是拍攝隨機java在我的代碼中拋出java.util.ConcurrentModificationException

public void enemyAttackStrategy() { 

    // Fire at when at around the 1/4, 1/2 and 3/4 in a random direction 
    int width = Gui.getInstance().getWidth(); 
    int firstPoint = width/4 ; 
    int secondPoint = firstPoint * 2; 
    int thirdPoint = firstPoint * 3; 

    int dist = 2; 

    boolean nearFirst = (getX() - firstPoint) < 3 && (getX() - firstPoint > 0) ; 
    boolean nearSecond = (getX() - secondPoint) < 3 && (getX() - secondPoint > 0) ; 
    boolean nearThird = (getX() - thirdPoint) < 3 && (getX() - thirdPoint > 0); 

    if(nearFirst || nearSecond || nearThird){ 

     //System.out.println("near!!!!!!!!" + (firstPoint) + " " + (secondPoint) + " " + (thirdPoint)); 
     Game.getInstance().enemyShot(); 
    } 

的代碼和創建enemybullet代碼

public void enemyShot() { 
    Bullet bullet = new Bullet("EnemyBullet", "Bullet.png", 14); 
    bullets.add(bullet); 
    int minSpeed = -15; 
    int xPosition = enemyShip.getX(); 
    int yPosition = enemyShip.getY(); 
    int xSpeed = random.nextInt(30) + minSpeed; 
    int ySpeed = random.nextInt(30) + minSpeed; 

    addToWorld(bullet, xPosition, yPosition, xSpeed, ySpeed, 2); 

    //System.out.println("Added Enemy Bullet"); 
} 

這是for循環的指我

public void timer() { 


    for (Tame oneTame : tames) { 
     tame.timeTick();//} 
     } 

,這是錯誤

java.util.ConcurrentModificationException 
at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:886) 
at java.util.ArrayList$Itr.next(ArrayList.java:836) 
at GameFrameworkJavaFX.Game.timeTick(Game.java:135) 
+3

您尚未發佈所有相關代碼,請告訴我們正在調用'enemyAttackStrategy()':)的循環 – alfasin 2015-03-08 21:38:31

+0

調用enemyAttackStrategy()的循環處於敵方階級中。但java.util.ConcurrentModificationException引用了我在遊戲類中的for循環。 – 2015-03-08 21:43:37

+0

發佈[SSCCE](http://sscce.org/)。也看看http://stackoverflow.com/questions/223918/iterating-through-a-list-avoiding-concurrentmodificationexception-when-removing – Pshemo 2015-03-08 21:44:19

回答

2

如果有兩個線程正在修改相同的代碼,則會發生ConcurrentModificationException。如果每個循環修改數組的內容,那麼通常會導致這種情況。有關該特定問題的更多詳細信息,請參閱this question。我不知道這是什麼原因導致問題,但像@alfasin評論,我們不能回答這個問題,沒有看到調用這些方法的代碼。

編輯:看到你剛剛發佈的代碼,它看起來很可能是這種情況。再次,請查看this question,因爲這似乎是其他人擁有完全相同類型的錯誤。

+1

「*如果您有兩個線程正在修改相同的代碼*」,則會發生ConcurrentModificationException,因爲您注意到這可能也是由一個線程引起的,如果它修改了他所迭代的集合。 「*我不知道這是什麼原因導致問題*」在這種情況下,您不應該將其作爲答案發布。當你獲得50點聲望點時,你將能夠留下評論,所以在你獲得此特權之前,不要將評論張貼爲答案。 – Pshemo 2015-03-08 21:49:47

+1

有點苛刻!答案雖然沒有完全解決問題,但包含可能有助於OP追蹤問題的有用信息。 – NickJ 2015-03-08 21:52:58

+0

我想補充說,當你改變你正在迭代的集合(singlethreaded)時,這個異常也會發生。加一。 – alfasin 2015-03-08 22:31:00

相關問題