如何限制CPU使用率?

时间:2017-09-28 01:05:48

标签: java cpu game-loop

如何使用此代码限制Java游戏的CPU使用率?我认为一种方法可能是使用Thread.sleep(),但前提是我可以计算时间或类似的东西。有人可以帮助我吗?

public void run(){
    this.requestFocus();
    long lastTime = System.nanoTime();
    double amountOfTicks = 60.0;
    double ns = 1000000000 / 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();
            delta--;
        }
        render();
        frames++;

        if(System.currentTimeMillis() - timer > 1000){
            timer += 1000;
            frames = 0;
        }
    }
    stop();     
}

1 个答案:

答案 0 :(得分:0)

除缺失的部分外,这看起来非常简单。考虑您想要以固定的速率更新。

while(isRunning){


    tick();
    render();
    long now = System.nanoTime();
    double delta = now - lastTime;
    double remaining = delta - ns;
    if(remaining>1000){
        try{
             Thread.sleep((int)(remaining/1000));
        } catch(InterruptedException e){
             throw new RuntimeException(e);
        }
    }

    frames++;
    lastTime = System.nanoTime();
    if(System.currentTimeMillis() - timer > 1000){
        timer += 1000;
        frames = 0;
    }
}