import java.util.Random;

/**
 * A producer puts the integers 1,...,n, where n is smaller than or equal to ITERATION,
 * in the buffer.
 *
 * @version     1.1    February 7, 2000
 * @author      Franck van Breugel
 * @see Buffer
 */
public class Producer extends Thread 
{
    private static int producers = 0; // number of producers

    public static final ThreadGroup PRODUCERS = new ThreadGroup("Producers");

    private Buffer buffer;            // the buffer where this producer puts its elements
    private int id;                   // number of this producer

    /**
     * Constructs a producer which puts elements in the specified buffer.
     *
     * @param buffer The buffer where this producer puts its elements.
     */
    public Producer(Buffer buffer)
    {
        super(PRODUCERS, "producer");
        this.buffer = buffer;
        setId(this);
    }

    /**
     * Sets the number of the specified producer.
     *
     * @param producer The producer whose number is set.
     */
    private static synchronized void setId(Producer producer)
    {
        producers++;
        producer.id = producers;
    }

    /**
     * If this producer is the last producer to stop, then signal the
     * specified buffer.
     *
     * @param buffer The buffer to be signalled.
     */    
    private static synchronized void finish(Buffer buffer)
    {
        Producer.producers--;
        if (Producer.producers == 0)
	{
	    buffer.setDone();
	}
    }

    /** Maximal number of elements to be put in the buffer. */
    private static final int ITERATION = 20;

    /** Maximal delay in miliseconds */
    private static int MAX_DELAY = 9999;

    /** 
     * Puts the integers 1,...,n, where n is smaller than or equal to ITERATION,
     * in the buffer. 
     */
    public void run() 
    {
        Random generator = new Random();

        boolean isInterrupted = false;
	int i = 0;
        while (i < ITERATION && !isInterrupted)
	{
            try
            {
                buffer.put(new Integer(i));
                System.out.println("Producer " + id + " has put " + i);
	        Thread.sleep((long) generator.nextInt(MAX_DELAY));
	    }
            catch (InterruptedException e)
	    {
	        isInterrupted = true;
	    }
            isInterrupted |= isInterrupted();
            i++;
	}
        if (!isInterrupted)
	{
            finish(buffer);
	}
    }
}









