running a while loop on an interval
<p>I am building a game with a good emphasis on physics. Therefore I need the game to run on a very specific interval. Current code:</p>

<pre><code>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 &gt; 0){
                Thread.sleep(sleep);
            }else{
                System.err.println("Warning: program runtime exceeded period");
            }
        }catch(Exception ex){}

        gameTime += period;
    }
}
</code></pre>

<p>This is not working as expected. Currently the main thread is executing without sleeping at all, and the "Warning: program runtime exceeded period" warning is firing.</p>

<p>Previously I was using System.currentTimeMillis(), but it was not accurate enough for my purposes, so I switched to System.nanoTime()</p>

<p>Increasing the period actually serves to speed up the program, while reducing it slows it down.</p>

<p>Is there a simple logic faw? is my understanding of System.nanoTime() off? or is there a better way to run the methods operateEntities, dispose, and update on a specific interval?</p>

<p>EDIT: for the record, the program does not take more than .02s to complete. It has been tested</p>
