//======================================================================
// Synchronizing on a Statement block
//======================================================================
public class Sync3 extends Thread 
{
    static String[] msg = {"Java","is","hot","aromatic","and","invigorating"};
                            
    public static void main(String[] args) 
    {
        Sync3 t1 = new Sync3("t1: ");           //create a thread - obj of this class
        Sync3 t2 = new Sync3("t2: ");           //and pass it a name
        
        t1.start();				//run thread
        t2.start();
        
        boolean t1Running = true;
        boolean t2Running = true;
        
        while (t1Running) 
            if (! t1.isAlive())					//is thread still alive
            {
                t1Running = false;
                System.out.println("t1 thread is dead.");
            }
        while (t2Running) 
            if (! t2.isAlive())
            {
                t2Running = false;
                System.out.println("t2 thread is dead.");
            }
    }                            
                                
    public Sync3(String name)                       //constructor
    {
        super(name);                                //have superclass store the name
    }
        
    public void run() 
    {
        synchronized(System.out)                    //synchronize & lock System.out object 
        {                                           //all output for thread 1 comes out first
            for(int i=0; i < msg.length; i++) 
            {
                randomWait();
                System.out.println(getName() + msg[i]);
            }    
        }
    }

    void randomWait() {
        try 
        {
            Thread t = Thread.currentThread();

            t.sleep( (long) (Math.random()*2000) );         //up to 2 seconds
        } 
        catch(InterruptedException e) 
        {
            System.out.println("Interrupted!");
        }
    }    
}