title: Synchronized methods to avoid deadlock
body: <p>I have two synchronized methods and I'm using the mediator design pattern. 
  I'm trying to avoid deadlocks, which is (from what I understand) for example when a thread has a lock on a variable res1 but needs a lock on variable res2. The other thread needs the lock for res1 but has the lock for res2 - resulting in a deadlock, right? </p>
  
  <p>Assuming my understanding of deadlocks are correct, then my question is whether or not I have solved the issue of deadlock in this code? </p>
  
  <p>I have two synchronized methods and two threads.</p>
  
  <pre><code>public class Producer extends Thread {
      private Mediator med;
      private int id;
      private static int count = 1;
  
      public Producer(Mediator m) {
          med = m;
          id = count++;
      }
  
      public void run() {
          int num;
          while(true) {
              num = (int)(Math.random()*100);
              med.storeMessage(num);
              System.out.println("P-" + id + ": " + num);
          }
      }
  }
  </code></pre>
  
  <hr>
  
  <pre><code>public class Consumer extends Thread {
      private Mediator med;
      private int id;
      private static int count = 1;
  
      // laver kopling over til mediator
      public Consumer(Mediator m) {
          med = m;
          id = count++;
      }
  
      public void run() {
          int num;
          while(true) {
              num = med.retrieveMessage();
              System.out.println("C" + id + ": " + num);
          }
      }
  }
  </code></pre>
  
  <hr>
  
  <pre><code>public class Mediator {
      private int number;
      private boolean slotFull = false;
  
      public synchronized void storeMessage(int num) {
          while(slotFull == true) {
              try {
                  wait();
              } catch (InterruptedException e) {
                  e.printStackTrace();
              }
          }  
          slotFull = true;
          number = num;
          notifyAll();
      }
  
      public synchronized int retrieveMessage() {
          while(slotFull == false) {
              try {
                  wait();
              } catch (InterruptedException e) {
                  e.printStackTrace();
              }
          }
          slotFull = false;
          notifyAll();
          return number;
      }
  }
  </code></pre>
  
  <hr>
  
  <pre><code>public class MediatorTest {
      public static void main(String[] args) {
          Mediator mb = new Mediator(); 
          new Producer(mb).start();
          new Producer(mb).start();
          new Producer(mb).start();
  
          new Consumer(mb).start();
          new Consumer(mb).start();
      }
  }
  </code></pre>