[英]Java - Thread.sleep inside run method
I'm following a tutorial and below is the run method to generate logic and frame updates. 我正在学习一个教程,下面是生成逻辑和帧更新的run方法。 I understand how the ticks are updated 60 ticks/second but I don't understand how we adjust frame per second here.
我理解滴答是如何更新60滴/秒,但我不明白我们如何调整每秒帧数。
Right now with Thread.sleep(2), frame per second is around 460. Without it the numbers go way up, around 10 million updates per second. 现在使用Thread.sleep(2),每秒帧数大约为460.没有它,数字会上升,每秒大约1000万次更新。 The code Thread.sleep(2) suspends the thread for only 2 milliseconds right?
代码Thread.sleep(2)暂停线程仅2毫秒对吗? Why/how does Thread.sleep exactly work here to drop it so low?
Thread.sleep为什么/如何正确地在这里工作以降低它?
Isn't it simpler to create a nsPerFrame = 1000000000D/ (FPS)D to set whatever FPS I want the way he did with ticks? 是不是更简单的创建一个nsPerFrame = 1000000000D /(FPS)D来设置我想要的方式与刻度线的方式?
public void run(){
long lastTime = System.nanoTime();
double nsPerTick = 1000000000D / 60D;
int frames = 0;
int ticks = 0;
long lastTimer = System.currentTimeMillis();
double delta = 0;
while(running){
long now = System.nanoTime();
delta += (now - lastTime) / nsPerTick;
lastTime = now;
while(delta >= 1){
ticks++;
tick();
delta-= 1;
}
try{
Thread.sleep(2);
} catch(InterruptedException e){
e.printStackTrace();
}
frames++;
render();
if(System.currentTimeMillis() - lastTimer >= 1000){
lastTimer += 1000;
System.out.println(ticks + "," + frames);
frames = 0;
ticks = 0;
}
}
}
Well sleep(2)
is called repeatedly in your running
-loop so the hard upper limit in this case is 500 cycles per second (1000 ms divided by 2 ms), and your measured 460 fps is pretty close to that. 在你的
running
-loop中重复调用well sleep(2)
,因此在这种情况下硬上限是每秒500个周期(1000 ms除以2 ms),你测得的460 fps非常接近。
Sure enough you can adjust the sleep duration according to your needs and if needed stuff it into the somewhat higher-precision method Thread#sleep(long, int)
where the second parameter is "nanos" (take a look at the docu for caveats!). 果然你可以根据你的需要调整睡眠持续时间,如果需要的话,可以把它填入更高精度的方法
Thread#sleep(long, int)
,其中第二个参数是“nanos”(看看文档中的注意事项! )。
The formula for your case is FPS = 1000 ms / sleep duration in ms
. 你的情况的公式是
FPS = 1000 ms / sleep duration in ms
。 From which follows: sleep duration in ms = 1000 ms / FPS
. 从下面开始:
sleep duration in ms = 1000 ms / FPS
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.