【问题标题】:Separate thread for Java game logicJava游戏逻辑的独立线程
【发布时间】:2010-09-06 02:20:56
【问题描述】:

当我制作简单的单线程游戏时,我以与越来越著名的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() 方法?

【问题讨论】:

    标签: java multithreading


    【解决方案1】:

    您可以使用构造函数或类似 in 的 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();
    }
    

    【讨论】:

    • 就是这样!就像不久前我非常接近这个,但我在Gamegame 之间有一个=,你在其中写了private Game game; DOH!
    【解决方案2】:

    y Java 确实生锈了,所以如果有差异,请以其他用户为准。

    在我看来,你所拥有的一切都很好。当您调用 start() 时,会创建一个新的线程上下文并调用 run()。在run()中,你正在调用你想要的函数。

    您缺少的是线程对游戏一无所知。我个人的偏好是在游戏中实现一个线程,将逻辑放在它自己的线程上,该线程是游戏类的成员。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-02-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-15
      • 1970-01-01
      相关资源
      最近更新 更多