/* Example from "Java 2 Certification" by Jamie Jaworski p 176
   
   Implementing Runnable
   Program displays the message "Java is hot, aromatic and invigorating"
   one word at a time with each thread displaying the same message.
   The output is interleaved.
*/

class Thread2 {
    
    public static void main(String[] args) {
    
        // threads are created by passing a Runnable object
        // to the Thread constructor
        Thread t1 = new Thread(new MyClass("t1: "));
        Thread t2 = new Thread(new MyClass("t2: "));
        
        t1.start();
        t2.start();
        
        boolean t1IsAlive = true;
        boolean t2IsAlive = true;
        
        do {
            if(t1IsAlive && !t1.isAlive()) {
                t1IsAlive = false;
                System.out.println("t1 is dead.");
            }
            
            if(t2IsAlive && !t2.isAlive()) {
                t2IsAlive = false;
                System.out.println("t2 is dead.");
            }
        } while(t1IsAlive || t2IsAlive);
    }                            
}

class MyClass implements Runnable {

    static String[] msg = { "Java", "is", "hot,", "aromatic,",
                            "and", "invigorating." };
    String name;                            
    
    public MyClass(String id) {
        name = id;
    }
    
    public void run() {
        for(int i=0; i<msg.length; i++) {
            randomWait();
            System.out.println(name+msg[i]);
        }
    }
    
    void randomWait() {
        try {
            Thread.currentThread().sleep((long)(3000*Math.random()));
        } catch(InterruptedException e) {
            System.out.println("Interrupted!");
        }
    }
}
