简体   繁体   English

使用 gameLoop 时实现多线程的正确方法是什么

[英]What is the proper way to implement multi threading while using a gameLoop

I'm working on a game where I move a car image based on keyboard input.我正在开发一款基于键盘输入移动汽车图像的游戏。 Currently I'm using this game loop:目前我正在使用这个游戏循环:

private void runGameLoop() {
        window.setVisible();
        isRunning = true;
        final double FRAMES_PER_SECOND = 60;
        double timePerUpdate = 1000000000 / FRAMES_PER_SECOND;
        double timeFromLastUpdate = 0;
        long now;
        long last = System.nanoTime();
        while (isRunning) {
            now = System.nanoTime();
            timeFromLastUpdate += (now - last) / timePerUpdate;
            last = now;
            if(timeFromLastUpdate >= 1) {
                tick();
                render();
                timeFromLastUpdate--;
            }
        }
    }

The tick method updates the car image location, and the render method will render the image(with the new location) on screen. tick 方法更新汽车图像位置,render 方法将在屏幕上渲染图像(带有新位置)。 I want to have the calculations for the new image location on a separate thread, because at the moment the calculations are taking to long and causing a rendering lag.我想在单独的线程上计算新图像位置,因为目前计算时间很长并导致渲染延迟。 Is there a way to use multi threading while still implementing a game loop?有没有办法在实现游戏循环的同时使用多线程? Thanks in advance.提前致谢。

Perhpas you can do something similar to what Android does.也许你可以做一些类似于 Android 的事情。 In Android there is the mainthread which would be like your game loop.在 Android 中有一个主线程,就像你的游戏循环一样。 It has a Handler for runnables that are posted from background/concurrent threads to the mainthread.它有一个用于从后台/并发线程发布到主线程的可运行对象的处理程序。

So at every loop cycle the mainthread executes any runnables posted feom background threads.因此,在每个循环周期中,主线程都会执行发布 feom 后台线程的任何可运行对象。

Note, that the calculations should not be done in the runnables (which are executed in mainthread), only passing the results/updating stuff should be done in the runnables.请注意,计算不应在可运行对象(在主线程中执行)中完成,只应在可运行对象中传递结果/更新内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM