I wrote a simple applet to have as a base fr making games, and it’s already using up >50% of my CPU. I’m on a 3ghz P4 with 1.5gb ram, so I know it shouldn’t take up THAT much.
import java.awt.*; import java.applet.*; public class applettest extends Applet implements Runnable { long lastFrame; public void init() { (new Thread(this)).start(); } public void paint(Graphics g) { g.drawString('Welcome to Java!!', 50, 60 ); } public void run() { while(true) { // code here repaint(); try{ // wait 16 milliseconds to cap frame rate to 60 fps while (System.nanoTime() < lastFrame + 160000000) { Thread.yield(); } lastFrame = System.nanoTime(); } catch(Exception e){} } } }
Try replacing your busy wait with
This will guarantee that the time between frames is at least 16ms. If your render time is less than 16ms, and there aren’t any other threads hogging the CPU, it will run at 60fps.
Your original solution will enforce the 16ms minimum, but it has to keep polling the system time over and over (which uses the CPU) until the necessary amount of time has passed.
Notes:
repaint()is an asynchronous call (i.e. it will return immediately)