Java游戏逻辑的独立线程

时间:2010-09-06 02:20:56

标签: java multithreading

当我制作简单的单线程游戏时,我实现游戏逻辑的方式与日益着名的Space Invaders tutorial完成相同,如下所示:

public static void main(String[] args) { //This is the COMPLETE main method
    Game game = new Game(); // Creates a new game.
    game.gameLogic(); // Starts running game logic.
}

现在我想尝试在单独的线程上运行我的逻辑,但是我遇到了问题。我的游戏逻辑位于一个单独的类文件中,如下所示:

public class AddLogic implements Runnable {

    public void logic(){
        //game logic goes here and repaint() is called at end
    }

    public void paintComponent(Graphics g){
        //paints stuff
    }

    public void run(){
        game.logic();  //I know this isn't right, but I cannot figure out what to put here.  Since run() must contain no arguments I don't know how to pass the instance of my game to it neatly.
    }

}

......我的主要方法如下:

public static void main(String[] args) { //This is the COMPLETE main method
    Game game = new Game(); // Creates a new game.
    Thread logic = new Thread(new AddLogic(), "logic");  //I don't think this is right either
    logic.start();

}

如何正确调用游戏实例上的logic()方法?

2 个答案:

答案 0 :(得分:4)

你可以通过使用构造函数或

中的setter来传递你的游戏实例
public GameThread extends Thread {
  private Game game;

  GameThread(Game game) {
    this.game = game;
  }

  public void run() {
    game.logic();
  }
}

public static void main(String[] args) {
  GameThread thread = new GameThread(new Game());
  thread.start();
}

答案 1 :(得分:1)

y Java真的很生锈,如果存在差异,请与其他用户保持一致。

你所看到的对我来说没问题。当您调用start()时,将创建一个新的线程上下文并调用run()。在run()中,您正在调用所需的函数。

你缺少的是线程不了解游戏。我个人的偏好是在游戏中实现一个线程,将逻辑放在自己的线程上,这是一个类游戏的成员。