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

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

    private int count;
    private boolean stop;

    public CountDown( int count ) {
        this.count = count;
        this.stop = true;
    }

    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 );
            }
            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 CountDown limit");
            System.exit( 1 );
        }
        int limit = Integer.parseInt( args[0] );
        BufferedReader in
            = new BufferedReader(
                    new InputStreamReader(System.in));
        CountDown cd = new CountDown( limit );
        Thread t = new Thread( cd );
        // start the second thread.
        t.start();
        String line = null;
        while ( (line=in.readLine()) != null ){
            if ( line.equals("stop") ) {
                cd.stop();
                System.out.println("stop requested");
                break;
            }
            else if ( line.equals("quit") ) {
                System.out.println("quit main");
                break;
            }
            else {
                System.out.println("what?");
            }
        }
    }
}
