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

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

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

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

    /** 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 read, reads, and wakes up a waiting reader or writer if it 
       is the last active reader.
    */
    public void run() 
    {
        while (true) 
	{
            delay();
            monitor.read(number);
        }
    }
}
