/**
 * Demo illustrates several threads created
 * 1. by extending Thread
 * 2. implementing Runnable
 * 3. implementing an anonymous Runnable
 * Also illustrate priorities, getting a current thread,
 * interrupting, joining, and polite stopping.
 */
class ThreadExtends extends Thread
{
    public boolean stayAlive = true;
    
    public void politeStop( )
    {
        stayAlive = false;
    }
    
    public void run( )
    {
        System.out.println( "TXTNDS priority " + this.getPriority( ) );
        for( int i = 0; i < 10 && stayAlive; i++ )
        {
            System.out.println( "ThreadExtends " + i );
            try 
            {
                Thread.sleep( 200 );
            }
            catch( InterruptedException e )
            {
            }
        }
    }
}

class ThreadsRunMethod implements Runnable
{
    public void run( )
    {
        Thread self = Thread.currentThread( );
        System.out.println( "TRM priority " + self.getPriority( ) );
        for( int i = 0; i < 10; i++ )
        {
            System.out.println( "ThreadsRunMethod " + i );
            if ( i == 6 )
            {
                ThreadDemo.mainThread.interrupt( );
                ((ThreadExtends)ThreadDemo.t1).politeStop( );
            }    
            try 
            {
                Thread.sleep( 200 );
            }
            catch( InterruptedException e )
            {
            }
        }
    }
}

class ThreadDemo
{
    public static Thread t1;
    public static Thread t2;
    public static Thread t3;
    public static Thread mainThread;
    
    public static void main( String[] args )
    {
        mainThread = Thread.currentThread( );
        t1 = new ThreadExtends( );
        t2 = new Thread( new ThreadsRunMethod( ) );
        t3 = new Thread( new Runnable( )
            {
                public void run( )
                {
                    for( int i = 0; i < 10; i++ )
                    {
                        System.out.println( "AnonymousRun " + i );
                        try 
                        {
                            Thread.sleep( 200 );
                        }
                        catch( InterruptedException e )
                        {
                        }
                    }
                }
            }        
        
        );
        
        t2.setPriority( Thread.MAX_PRIORITY );
        t1.start( );
        t2.start( );
        t3.start( );
        
        try 
        {
            t1.join( ); t2.join( ); t3.join( );
        }
        catch( InterruptedException e )
        {
            System.out.println( "Main is interrupted!!!" );
        }
        
        System.out.println( "Main program is done" );
    }
}
