Concurrent Programming with Java
Lab Manual, Version 1.0, F. Astha Ekadiyanto, 2002.

[Contents] [Next] [Previous]

Lab 5: Monitors and Thread Synchronization 1


Consumer-Producer Demonstration: Consumer Class

Actually the Consumer Class is very much similar to the Mieter Class in the Race Condition section (observe the run() and read() method definition).

The Consumer Class codes are:

/**
 * The class Consumer implements a consumer.
 * @author Stephan Fischli
 * @version 1.1
 */
public class Consumer extends Thread
{
   public static final int PAUSING = 0;
   public static final int READING = 1;
   public static final int CONSUMING = 2;
  /**
   * The buffer used by the consumer.
   */
   private Buffer buffer;
  /**
   * The state of the consumer.
   */
   private int state;
  /**
   * Constructs a Consumer object.
   * @param buffer the buffer to be used by the consumer
   */
   public Consumer( Buffer buffer )
   {
        this.buffer = buffer;
        state = PAUSING;
   }
  /**
   * Returns the state of the consumer.
   */
   public int state()
   {
        return state;
   }
  /**
   * Starts the consumer.
   */
   public void run()
   {
        while ( true ) {
             pause();
             Object data = read();
             consume( data );
        }
   }
  /**
   * Lets the consumer pause.
   */
   public void pause()
   {
        state = PAUSING;
        int time = (int)(20000*(0.5 + Math.random()));
        try { sleep( time ); }
        catch ( InterruptedException e ) {}
   }
  /**
   * Lets the consumer read data from the buffer.
   * @return the read data
   */
   public Object read()
   {
        state = READING;
        return buffer.get();
   }
  /**
   * Lets the consumer consume data.
   * @param the data to consume
   */
   public void consume( Object data )
   {
        state = CONSUMING;
        int time = (int)(10000*(0.5 + Math.random()));
        try { sleep( time ); }
        catch ( InterruptedException e ) {}
   }
}


[Contents] [Next] [Previous]