Capped framerate and "getting" FPS

I’m trying to learn how to cap my framerate to 60 using JUST Java. I have a simple understanding yet far from perfect or even knowing how to get it working. I just know I need to get the time --> do rendering updates etc --> get the time again. I then need to do something with the difference (lastTime - firstTime) but I’m not sure what.

Any help with game looping and getting/setting the FPS would be much appreciated.

~Shazer2


long frameNanoseconds = 1000*1000*1000 / DESIRED_FPS;

long startTime = System.nanoTime();

while(gameIsRunning){

    updateAndRenderEverything();

    long timeTaken = System.nanoTime() - startTime;
    if(timeTaken < frameNanoseconds){
        int sleepMillis = (frameNanoseconds - timeTaken) / (1000*1000);
        try{
            Thread.sleep(sleepMillis);
        catch(InterruptedException ex){
            ex.printStackTrace();
        }
    }

    startTime += frameNanoseconds;

}


For Thread.sleep(…) to work reliably on windows, use the following trick:


new Thread() {
    {
        setDaemon(true);
        start();
    }
    
    public void run() {
        while(true) {
            try{
                Thread.sleep(Long.MAX_VALUE);
            }
            catch(Exception exc) {}
        }
    }
};