/* Three independent threads, including the main() thread.
*  
* Thread one prints the letter 'a' 200 times.
* Thread two prints the integers 1 through 200.
*
* main() thread prints a message before terminating.
*/
public class TestJoin {
    private Thread printA;
    private Thread printC;

    public TestJoin(String[] args) {
        // Create threads; second receives reference to first (for join()).
        Thread printA = new Thread (new PrintChar('a', 200));
        Thread printNum = new Thread (new PrintNum(200, printA));

        // start the threads
        printA.start(); 
        printNum.start();

        // Join on threads if given anything at command line.
        if ( args.length > 0 ) {
            try { 
                printA.join();
                printNum.join();
            } catch ( InterruptedException e ) {
            }
        }
        System.out.println("\nMain thread terminated.");
    } 

    public static void main(String args[]) {
        TestJoin test = new TestJoin(args);
    } 
} 


class PrintChar implements Runnable {
    private char charToPrint; // the character to print
    private int times; // The times to repeat

    // Construct a thread with specified character and number
    // of times to print the character
    public PrintChar(char c, int t) {
        charToPrint = c;
        times = t;
    } 

    // Override the run() method to tell the system
    // what the thread will do
    public void run() {
        for (int i=0; i<=times; i++) {
            System.out.print(" " + charToPrint);
        }
    } 
} 

class PrintNum implements Runnable {
    private int lastNum; // the last number to print
    private Thread waitOnThread; // the thread to wait on

    // Construct a thread with the last number
    public PrintNum(int n, Thread t) {
        lastNum = n;
        waitOnThread = t;
    } 

    // Override the run() method to tell the system
    // what the thread will do
    public void run() {
        try {
            waitOnThread.join();
        } catch (InterruptedException ex) {}


        for (int i=0; i<=lastNum; i++) {
            System.out.print(" " + i);
        }
    } 
} 

