package JThread.examples.crew;

import JThread.stream.*;

public class Writer extends Thread implements java.io.Serializable
{
    public Writer( 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.write( name, name + "/" + i );
                } catch ( InvalidUnlock iu ) {
                    System.out.println( "Reader " + name + ": InvalidUnlock" );
                }
            
                try {
                    Thread.currentThread().sleep( (int)(Math.random()*600.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;
}