CIS 260 The wait method

While it may seem that we have solved our problems, there are still a couple of wrinkles that can help our coding. The synchronize keyword works by setting a lock. No other synchronized method in that object can be entered while the lock is in place. Using sleep() doesn't help because sleep() doesn't release the lock. The method wait() does release the lock. The wait() method can only be used within synchronized methods.

public class TThread9 {
   public static void main(String[] args) {
      Adder t = new Adder();
      t.start();
      (new TestSync(t)).start();
      t = null;
   }
}

class Adder extends Thread {
   private int count1 = 0, count2 = 0, count3 = 0;
   private boolean done = false;
   private String[] sym = { "-", "\\", "|", "/" };

   public synchronized void run() {
      while (count1 <= 100) {
         count1++; count2++; count3++;
         System.out.print("\r" + sym[count1 % 4]);
         try {
            wait(50);
         } catch (InterruptedException e) {
            System.out.println("Application Interrupted");
         }
      }
      done = true;
   }

   public synchronized boolean check() {
      int c1, c2, c3;
      c1 = count1; c2 = count2; c3 = count3;
      if ((c1 != c2) || (c2 != c3))
         System.out.println("\rNot synced: " + c1 +
                            ", " + c2 + ", " + c3);
      return !done;
   }
}

class TestSync extends Thread {
   private int totAccess = 0;
   private Adder t1 = null;

   public TestSync(Adder t) { t1 = t; }

   public void run() {
      while (t1.check()) ++totAccess;
      System.out.println("\nTotal sync accesses: " + totAccess);
   }
}
// \
// Total sync accesses: 15427127

Previous: synchronized code blocks

Next: the notify method