import java.io.*;
import java.io.InputStreamReader;

/**
 * Count down to termination unless stopped.
 */
public class CountDown1 implements Runnable {

    private int count;
    private boolean stop;
    private Thread th;

    public CountDown1( int count, Thread th ) {
        this.count = count;
        this.stop = true;
        this.th = th;
    }

    public void stop() {
        stop = false;
    }

    public void run() {
        try {
            for( int i = 0; i < count && stop ; i++ ) {
                System.out.println( i );
                Thread.sleep( 1000 );
            }
            if ( stop ) {
                System.out.println("too late");
                //System.exit( 0 );
                th.interrupt();
            }
            else {
                System.out.println("stop aborted");
            }
        }
        catch( InterruptedException ex ) {
        }
    }

    /**
     * The initial thread starts with main.
     */
    public static void main( String[] args ) throws IOException {
        if ( args.length != 1 ) {
            System.out.println("java CountDown1 limit");
            System.exit( 1 );
        }
        int limit = Integer.parseInt( args[0] );
        BufferedReader in
            = new BufferedReader(
                    new InputStreamReader(System.in));
        Thread cur = Thread.currentThread();
        CountDown1 cd = new CountDown1( limit, cur );
        Thread t = new Thread( cd );
        // start the second thread.
        t.start();
        String line = null;
        while ( true ) {
            try {
                line = in.readLine();
            }
            catch( java.io.InterruptedIOException ex ) {
                System.out.println("io interrupted, exiting");
                break;
            }
            if ( line.equals("stop") ) {
                cd.stop();
                System.out.println("stop requested");
                break;
            }
            else {
                System.out.println("what?");
            }
            if (cur.isInterrupted() ) 
                System.out.println("isInterrupted() is true");
        }
    }
}
