/* Example of Synchronized Threads from
   "Java 2 Certification" by Jamie Jaworski p182
   
   Example shows how synchronized blocks can be used on objects
   to coordinate access to them by multiple threads.
*/

class Thread4 extends Thread {
    static String[] msg = { "Java", "is", "hot,", "aromatic,",
                            "and", "invigorating." };
                            
    public static void main(String[] args) {
        Thread4 t1 = new Thread4("t1: ");
        Thread4 t2 = new Thread4("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);
    }                            
                                
    public Thread4(String id) {
        super(id);
    }
    
    void randomWait() {
        try {
            Thread.currentThread().sleep((long)(3000*Math.random()));
        } catch(InterruptedException e) {
            System.out.println("Interrupted!");
        }
    }    

    
    public void run() {
        synchronized(System.out) {
            for( int i=0; i<msg.length; i++ ) {
                randomWait();
                System.out.println(getName() + msg[i]);
            }    
        }
    }
}   

   
