日期:2014-05-20 浏览次数:20794 次
long startTime = System.currentTimeMillis(); //一帧的绘制运算 消耗时间不同 ... /** 计算出更新本次帧所消耗的毫秒数 **/ int diffTime = (int) (System.currentTimeMillis() - startTime); /** 确保每次更新时间为50帧 **/ //方式1 线程休眠时间不同的影响需要查一下,再决定用何种方式 try { Thread.sleep(TIME_IN_FRAME-diffTime); } catch (InterruptedException e) { e.printStackTrace(); } //方式2 用线程等待 while (diffTime <= TIME_IN_FRAME) { diffTime = (int) (System.currentTimeMillis() - startTime); //线程等待 Thread.yield(); }
public void run( ) /* Repeatedly: update, render, sleep so loop takes close to period ms */ { long beforeTime, timeDiff, sleepTime; beforeTime = System.currentTimeMillis( ); running = true; while(running) { gameUpdate( ); gameRender( ); paintScreen( ); timeDiff = System.currentTimeMillis( ) - beforeTime; sleepTime = period - timeDiff; // time left in this loop if (sleepTime <= 0) // update/render took longer than period sleepTime = 5; // sleep a bit anyway try { Thread.sleep(sleepTime); // in ms } catch(InterruptedException ex){} beforeTime = System.currentTimeMillis( ); } System.exit(0); } // end of run( )