public void run() { long start, end, sleepTime; while (running) { start = System.currentTimeMillis(); if (gridSet) { grid.scanStep(); } repaint(); end = System.currentTimeMillis(); // Sleep to match FPS limit sleepTime = (1000 / framerate) - (end - start); if (sleepTime > 0) { try { Thread.sleep(sleepTime); } catch (InterruptedException e) { thread.interrupt(); } } } }