我在java中使用线程时遇到了一些问题

时间:2018-06-06 23:54:20

标签: java game-loop

我一般都习惯使用线程,有人可以解释为什么我有时会遇到这种异常:

Exception in thread "Thread-3" java.lang.NullPointerException
    at Game.tick(Game.java:96)
    at Game.run(Game.java:73)
    at java.lang.Thread.run(Unknown Source)

当游戏开始或我正在玩游戏时会发生这种情况。这个错误是如此不一致,当它决定弹出时,我不知道是什么导致它。

这是run和tick方法:

public void run(){
    this.requestFocus();
    long lastTime = System.nanoTime();
    double amountOfTicks = 60.0;
    double ns = 100000000 / amountOfTicks;
    double delta = 0;
    long timer = System.currentTimeMillis();
    int frames = 0;
    while(isRunning) {
        long now = System.nanoTime();
        delta += (now - lastTime) / ns;
        lastTime = now;
            while(delta >= 1) {
                tick();
                //updates++;
                delta--;
            }
       render();
       frames++;

       if(System.currentTimeMillis() - timer > 1000) {
        timer += 1000;
        frames = 0;
        //updates = 0;
       }
    }
    stop();
}
public void tick(){

    for(int i = 0; i < handler.object.size(); i++){
        if(handler.object.get(i).getId() ==ID.Player){
            camera.tick(handler.object.get(0));
        }
    }
    handler.tick();
}

如果这篇帖子与线程上的其他帖子非常相似我很抱歉,我只需要一些快速修复(如果有的话)。我忘了提到每次游戏启动时错误都不同,例如:

Exception in thread "Thread-3" java.lang.NullPointerException
at Enemy.tick(Enemy.java:59)
at Handler.tick(Handler.java:13)
at Game.tick(Game.java:101)
at Game.run(Game.java:73)
at java.lang.Thread.run(Unknown Source)

Exception in thread "Thread-3" java.lang.NullPointerException
at Enemy.collision(Enemy.java:105)
at Enemy.tick(Enemy.java:31)
at Handler.tick(Handler.java:13)
at Game.tick(Game.java:101)
at Game.run(Game.java:73)
at java.lang.Thread.run(Unknown Source)

如果它有帮助,这也是处理程序类:

    import java.awt.Graphics;
import java.util.ArrayList;

public class Handler {

    ArrayList<GameObject> object = new ArrayList<GameObject>();


    public void tick(){
        for(int i = 0; i < object.size(); i++){
            GameObject tempObject = object.get(i);

            tempObject.tick();
        }
    }

    public void render(Graphics g){
        for(int i = 0; i < object.size(); i++){
            GameObject tempObject = object.get(i);

            tempObject.render(g);
        }
    }


    public void addObject(GameObject tempObject){
        object.add(tempObject);
    }

    public void removeObject(GameObject tempObject){
        object.remove(tempObject);
    }

    public void addObjectSpec(int i, GameObject tempObject){
        object.add(i, tempObject);
    }

}

1 个答案:

答案 0 :(得分:-1)

虽然没有足够的信息来写出确凿的答案,但您应该检查以下内容:

  • 确保ID类具有名为Player
  • 的非空字段
  • 确保相机不为空
  • 确保处理程序不为空
  • 确保handler.object不为null
  • 检查所有线程安全对象
  • 确保在通过循环时没有操纵handler.objects