Concurrent Programming with Java
Lab Manual, Version 1.0, F. Astha Ekadiyanto,
2002.
Similar to Consumer Class, the Producer Class has the same behaviour as the Postbote Class in the Race Condition Section (observe the run() and write() method definition).
The Producer Class codes are:
/** * The class Producer implements a producer. * @author Stephan Fischli * @version 1.1 */ public class Producer extends Thread { public static final int PAUSING = 0; public static final int PRODUCING = 1; public static final int WRITING = 2; /** * The buffer used by the producer. */ private Buffer buffer; /** * The state of the producer. */ private int state; /** * Constructs a Producer object. * @param buffer the buffer to be used by the producer */ public Producer( Buffer buffer ) { this.buffer = buffer; state = PAUSING; } /** * Returns the state of the producer. */ public int state() { return state; } /** * Starts the producer. */ public void run() { while ( true ) { pause(); Object data = produce(); write( data ); } } /** * Lets the producer pause. */ public void pause() { state = PAUSING; int time = (int)(20000*(0.5 + Math.random())); try { sleep( time ); } catch ( InterruptedException e ) {} } /** * Lets the producer produce data. * @return the produced data */ public Object produce() { state = PRODUCING; int time = (int)(10000*(0.5 + Math.random())); try { sleep( time ); } catch ( InterruptedException e ) {} return new Object(); } /** * Lets the producer write data to the buffer. * @param data the data to write */ public void write( Object data ) { state = WRITING; buffer.put( data ); } } |