Source of Producer.java


  1: //Producer.java
  2: //Producer's run method controls a thread that
  3: //stores values from 1 to 4 in sharedLocation.
  4: 
  5: public class Producer extends Thread
  6: {
  7:    private Buffer sharedLocation; // reference to shared object
  8: 
  9:    // constructor
 10:    public Producer( Buffer shared )
 11:    {
 12:        super( "Producer" );
 13:        sharedLocation = shared;
 14:    }
 15: 
 16:    // store values from 1 to 4 in sharedLocation
 17:    public void run()
 18:    {
 19:       for ( int count = 1; count <= 4; count++ )
 20:       {  
 21:          
 22:          // sleep 0 to 3 seconds, then place value in Buffer
 23:          try
 24:          {
 25:             Thread.sleep( ( int ) ( Math.random() * 3001 ) );
 26:             sharedLocation.set( count );  
 27:          }
 28: 
 29:          // if sleeping thread interrupted, print stack trace
 30:          catch ( InterruptedException exception )
 31:          {
 32:             exception.printStackTrace();
 33:          }
 34: 
 35:       } // end for
 36: 
 37:       System.err.println( getName() + " done producing." + 
 38:          "\nTerminating " + getName() + ".");
 39: 
 40:    } // end method run
 41: 
 42: } // end class Producer
 43: