CIS 260 Shared Resource Problems II

This example is a reorganization of the previous page's example intended to make this problem a little more object oriented. It also leads us into the next examples which are concerned with solving the shared resource problem. All the code for accessing the variables, and the variables themselves are now contained within a single object. A second object is created to do the synchronization testing in a second thread.

public class TThread6 {
   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;

   public void run() {
      while (count1 <= 100) {
         count1++; count2++; count3++;
         try {
            Thread.sleep(50);
         } catch (InterruptedException e) {
            System.out.println("Application Interrupted");
         }
      }
      done = true;
   }

   public boolean check() {
      int 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("Total sync accesses: " + totAccess);
   }
}
// Not synced: 1, 2, 2
// Not synced: 10, 11, 11
// Not synced: 20, 21, 21
// Not synced: 26, 27, 27
// Not synced: 42, 42, 43
// Not synced: 58, 59, 59
// Not synced: 60, 60, 61
// Not synced: 71, 72, 72
// Not synced: 73, 74, 74
// Not synced: 77, 78, 78
// Not synced: 82, 83, 83
// Not synced: 94, 95, 95
// Total sync accesses: 97771455

Previous: shared resource problems I

Next: synchronized methods