Skip to Main Content
Killer Game Programming in Java
book

Killer Game Programming in Java

by Andrew Davison
May 2005
Intermediate to advanced content levelIntermediate to advanced
998 pages
26h
English
O'Reilly Media, Inc.
Content preview from Killer Game Programming in Java

Pausing and Resuming

Even with the most exciting game, there comes a time when the user wants to pause it (and resume later).

One largely discredited coding approach is to use Thread.suspend() and resume(). These methods are deprecated for a similar reason to Thread.stop();suspend() can cause an applet/application to suspend at any point in its execution. This can easily lead to deadlock if the thread is holding a resource since it will not be released until the thread resumes.

Instead, the Java documentation for the Thread class recommends using wait() and notify() to implement pause and resume functionality. The idea is to suspend the animation thread, but the event dispatcher thread will still respond to GUI activity. To implement this approach, I introduce an isPaused Boolean, which is set to true via pauseGame():

    // global variable
    private volatile boolean isPaused = false;

    public void pauseGame()
    { isPaused = true;   }


    public void run()
    // Repeatedly (possibly pause) update, render, sleep
    // This is not a good approach, and is shown for illustration only.
    { ...
      running = true;
      while(running) {
        try {
          if (isPaused) {
            synchronized(this) {
              while (isPaused && running)
                wait();
            }
          }
        } // of try block
        catch (InterruptedException e){}

        gameUpdate();   // game state is updated
        gameRender();   // render to a buffer
        paintScreen();  // paint with the buffer
   

        // sleep a bit
      }
      System.exit(0);
    } // end of run()

The isPaused flag is detected in run() and triggers a wait() call to suspend the animation ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Java Game Development with LibGDX: From Beginner to Professional

Java Game Development with LibGDX: From Beginner to Professional

Lee Stemkoski

Publisher Resources

ISBN: 0596007302Supplemental ContentErrata Page