package JThread.examples.crew;

import JThread.stream.*;

public class Reader extends Thread implements java.io.Serializable
{
    public Reader( String name, CrewedString crewedString, int cycles )
    {
        this.name = name;
        this.cycles = cycles;
        this.crewedString = crewedString;
        setName(name);
    }
    
    public void run()
    {
        long start_time = System.currentTimeMillis();
        try {
            System.out.println( "  ** " + name + " starts" );
            for( int i = 0; i<cycles; i++ )
            {
                try {
                    crewedString.read( name );
                } catch ( InvalidUnlock iu ) {
                    System.out.println( "Reader " + name + ": InvalidUnlock" );
                }
                
                try {
                    Thread.currentThread().sleep( (int)(Math.random()*100.0) );
                } catch ( InterruptedException e ) {
                    System.out.println( e.toString() );
                }
            }
        } catch (Exception e) { }
        long end_time = System.currentTimeMillis();
        System.out.println( "  ** " + name + " terminates in " + 
                        (end_time - start_time) + " ms.");
    }
    
    private String name;
    private int cycles;
    private CrewedString crewedString;
}
