0

So I'm currently just learning how to do this, and someone said that the code is inefficient because the thread is still running when nothing is updating. When I look at the CPU usage in the task manager, it shoots up to 35 - 45% and 20 in the CPU column when only a black screen is being rendered. Is there a way to make the thread sleep when the CPU isn't updating anything?

Thanks!

public void run() {

    long lastTime = System.nanoTime();
    long timer = System.currentTimeMillis();
    final double ns = 1000000000.0 / 60.0;         
    double delta = 0;

    int frames = 0;
    int updates = 0;

    while (running) {
        long now = System.nanoTime();
        delta += (now - lastTime) / ns;
        lastTime = now;
        while(delta >= 1) {
            update();
            updates++;
            delta--;
        }

        render();
        frames++;

        if(System.currentTimeMillis() - timer > 1000) {
            timer += 1000;
            updates = 0;
            frames = 0;
        }
    }
    stop(); 
}
Victor2748
  • 4,149
  • 13
  • 52
  • 89
Acecle
  • 13
  • 4
  • 1
    You make a thread sleep when not updating anything by having it be event-driven vs simply sitting in a tight loop. – Hot Licks Oct 24 '14 at 22:33
  • 1
    Calculate the difference between the tim it took to render/update the frame and the amount of time you might need to sleep (ie about 16 milliseconds for 60fps) then sleep (via `Thread.sleep`) for the difference... – MadProgrammer Oct 24 '14 at 22:33
  • http://docs.oracle.com/javase/tutorial/essential/concurrency/sleep.html – Radiodef Oct 25 '14 at 00:37

2 Answers2

0

You shouldn't render on your own threads. SWING is thread unsafe so all GUI operations should happen on the SWING thread. It just happens SWING has a thread specially made for this.

timer = new javax.swing.Timer(1000 / 60, this);
timer.start();


@Override
public void actionPerformed(ActionEvent e) {
    // Do your stuff (ignore 'e')
}
Mark Jeronimus
  • 9,278
  • 3
  • 37
  • 50
-2

The only good way of doing it, is to execute the yourThread.wait() when the game stops doing stuff, and then yourThread.notify() when the game makes an action again.

Victor2748
  • 4,149
  • 13
  • 52
  • 89