我正在建立一个非常注重物理学的游戏.因此我需要游戏以非常特定的间隔运行.当前代码:
public double period = .02; //this is the run interval in seconds
//main gameLoop
public void gameLoop(){
long startTime;
long sleep;
while(running){
startTime = System.nanoTime();
Graphics2D g = s.getGraphics();
operateEntities(g);
g.dispose();
s.update();
//figure out how long it must sleep to take .02s altogether
sleep = ((int)(period*1000) - (System.nanoTime() - startTime)*100000);
try{
if(sleep > 0){
Thread.sleep(sleep);
}else{
System.err.println("Warning: program runtime exceeded period");
}
}catch(Exception ex){}
gameTime += period;
}
}
Run Code Online (Sandbox Code Playgroud)
这没有按预期工作.目前主线程正在执行而根本没有休眠,并且"警告:程序运行时超出期限"警告正在触发.
以前我使用System.currentTimeMillis(),但它不够准确,所以我切换到System.nanoTime()
增加周期实际上可以加速程序,同时减少它会减慢程序.
有一个简单的逻辑faw?是我对System.nanoTime()的理解了吗?或者是否有更好的方法来运行特定时间间隔上的方法operateEntities,dispose和update?
编辑:为了记录,该程序不需要超过.02s完成.它已经过测试
java ×1