001    package pnc;
002    import cs101.awt.DisplayField;
003    
004    public
005    class Producer extends Thread {
006      private Buffer storage;
007      private DisplayField display;
008      private static int InstanceCount = 0;
009      private static Object Lock = new Object();
010    
011      public Producer(Buffer storage, DisplayField display) {
012        this.storage = storage;
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 + " producer(s) started.");
028        }
029    
030        // wait to see it
031        try { Thread.sleep(250); } 
032        catch (InterruptedException e) {}
033    
034        this.storage.produce();  
035        
036        synchronized(Lock) {
037        this.display.setText(Integer.toString(this.InstanceCount-1));
038        // tab over an approprate amount
039        for (int i = 0; i<this.InstanceCount-1; i++) 
040          System.out.print("    ");
041        System.out.println("Production complete.");
042        this.InstanceCount--;
043        
044        // if none are left waiting ...
045        if (this.InstanceCount == 0)
046          this.display.changeState(true);
047        }
048    
049      }
050    
051    }
052