001    package pnc;
002    import cs101.awt.DisplayField;
003    
004    public
005    class Consumer extends Thread {
006      private Buffer supply;
007      private DisplayField display;
008      private static int InstanceCount = 0;
009      private static Object Lock = new Object();
010    
011      public Consumer(Buffer supply, DisplayField display) {
012        this.supply = supply;
013        this.display = display;
014      }
015    
016      public void run() {
017        synchronized(Lock) {
018          this.InstanceCount++;
019          // if this is the first producer waiting ...
020          if (this.InstanceCount == 1) 
021            this.display.changeState(false);
022    
023          this.display.setText(Integer.toString(this.InstanceCount));
024          // tab over an approprate amount
025          for (int i = 0; i<this.InstanceCount-1; i++) 
026            System.out.print("    ");    
027          System.out.println(this.InstanceCount + " consumer(s) started.");
028        }
029    
030        // wait to see it
031        try { Thread.sleep(250); } 
032        catch (InterruptedException e) {}
033        this.supply.consume();
034    
035        synchronized(Lock) {
036          this.display.setText(Integer.toString(this.InstanceCount-1));
037          // tab over an approprate amount
038          for (int i = 0; i<this.InstanceCount-1; i++) 
039            System.out.print("    ");
040          System.out.println("Consumption complete.");
041          this.InstanceCount--;
042    
043          // if none are left waiting ...
044          if (this.InstanceCount == 0)
045            this.display.changeState(true);
046    
047        }
048    
049      }
050    
051    }
052    
053    
054    
055    
056    
057    
058    
059    
060    
061    
062    
063    
064    
065    
066    
067    
068    
069    
070    
071    
072    
073    
074