Java – is the tight loop broken?

Isn't the tight loop in the program bad?

I have an application with a two - threaded game physics simulator Updategame thread and rendering thread The rendering thread is limited by hibernating the thread for a few milliseconds (to achieve the frame rate I want), and the updategame thread (updating my GameObject position based on some physical equations) was previously limited by 10 milliseconds of sleep

However, I have not limited the updategame thread recently, and my simulation of object motion seems more realistic because I have taken out 10ms of sleep time Is thermal cycling or tight cycling bad?

private class UpdateTask implements Runnable
{
    private long prevIoUsTime = System.currentTimeMillis();
    private long currentTime = prevIoUsTime;
    private long elapsedTime;


    public void run()
    {
        while(true)
        {
        currentTime = System.currentTimeMillis();
        elapsedTime = (currentTime - prevIoUsTime); // elapsed time in seconds


        updateGame(elapsedTime / 1000f);

            try {
                Thread.currentThread().sleep(1);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        prevIoUsTime = currentTime;
        }
    }
}

In this example, I only slept for 1ms (according to my understanding of millisecond accuracy and how sleep function works, this may be more like 5-10ms. If I can't sleep, it starts to affect the accuracy of my collision detection and physical model

Is it a bad practice to have a tight cycle or cycle of 1ms sleep? Is there anything else I should do?

Solution

I read an article about efficient and effective execution of physical computing loops: fix your timestep!

When the game is running, it is usually the main application that users care about, so tight loop is not a big deal What should you do, but schedule your updates You should know - at the target frame rate - how long your frame must be executed You should measure the frame time and sleep only after subtracting the known frame time from the frame time In this way, your system will lock the frame rate without changing with the time required for frame rendering

Another thing is that I don't believe in thread Sleep has a very good resolution, more than 5 milliseconds. You may want to find a more accurate Java timer

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>