/**
   The Writer class simulates a writer.
  
   @author      Franck van Breugel
   @version     1.1    February 28, 2000
*/
public class Writer extends Thread 
{
    private static int writers = 0; // number of writers

    private int number;
    private Monitor monitor; // to access data shared amongst reader and writers

    /**
       Creates a Writer object with the specified monitor.

       @param monitor Monitor containing the shared data.
    */
    public Writer(Monitor monitor) 
    {
        this.monitor = monitor;
	number = writers++;
    }

    /** The maximum delay: 5000 miliseconds. */
    public static final int DELAY = 5000;

    /** Sleeps for a random amount of time between 0 and DELAY miliseconds. */
    private void delay() 
    {
        try 
	{
            sleep((int) (Math.random() * DELAY));
        } 
	catch (InterruptedException e) {}
    }

    /** 
       Sleeps for a random amount of time between 0 and DELAY miliseconds, waits until 
       it is allowed to write, writes, and wakes up a waiting reader or writer.     
    */
    public void run() 
    {
        while (true) 
	{
            delay();
            monitor.write(number);
        }
    }
}
