title: What does synchronized()/wait()/notifyAll() do in Java?
body: <blockquote>
    <p><strong>Possible Duplicate:</strong><br>
    <a href="https://stackoverflow.com/questions/1321747/java-synchronization">Java Synchronization</a>  </p>
  </blockquote>
  
  
  
  <p>I'm reading the book <em>Beginning Android Games</em>.</p>
  
  <p>It uses <code>synchronized()</code> a lot but I don't really understand what it does. I haven't used Java in a long time and I'm not sure if I ever used multithreading.</p>
  
  <p>In the Canvas examples it uses <code>synchronized(this)</code>. However in the OpenGL ES example, it creates an Object called <code>stateChanged</code> and then uses <code>synchronized(stateChanged)</code>. When the game state changes it calls <code>stateChanged.wait()</code> and then <code>stateChanged.notifyAll();</code></p>
  
  <p>Some code:</p>
  
  <pre><code>    Object stateChanged = new Object();
  
      //The onPause() looks like this:
      public void onPause()
          {
              synchronized(stateChanged)
              {
                  if(isFinishing())
                      state = GLGameState.Finished;
                  else
                      state = GLGameState.Paused;
  
                  while(true)
                  {
                      try
                      {
                          stateChanged.wait();
                          break;
                      } catch(InterruptedException e)
                      {
                      }
                  }
              }
          }
  //The onDrawSurface looks like this:
  public void onDrawFrame(GL10 gl)
      {
          GLGameState state = null;
          synchronized(stateChanged)
          {
              state = this.state;
          }
  
          if(state == GLGameState.Running)
          {
  
          }
  
          if(state == GLGameState.Paused)
          {
              synchronized(stateChanged)
              {
                  this.state = GLGameState.Idle;
                  stateChanged.notifyAll();
              }
          }
  
          if(state == GLGameState.Finished)
          {
              synchronized(stateChanged)
              {
                  this.state = GLGameState.Idle;
                  stateChanged.notifyAll();
              }
          }
      }
  
  //the onResume() looks like this:
  synchronized(stateChanged)
          {
              state = GLGameState.Running;
              startTime = System.nanoTime();
          }
  </code></pre>