FileDocCategorySizeDatePackage
JoinThread.javaAPI DocExample2157Tue May 01 16:43:38 BST 2001None

JoinThread.java

// Simple multiple thread demonstration using the Runnable interface

class JoinThread
  {
    public static void main(String args[])
      {
        JoinMe nrf = new JoinMe("first thread");
        JoinMe nrs = new JoinMe("second thread");
        JoinMe nrt = new JoinMe("third thread");
 
        //check see who is alive
        System.out.println("Thread one is alive:  " + nrf.rt.isAlive());
        System.out.println("Thread two is alive:  " + nrs.rt.isAlive());
        System.out.println("Thread three is alive:  " + nrt.rt.isAlive());
        
                 
                   
         try
            {
              // Instruct main thread to wait for other threads to finish
              nrf.rt.join();
              nrs.rt.join();
              nrt.rt.join();
                 
             }
         catch(InterruptedException e)
             {
               System.out.println("Main thread interrupted.");
             }
         System.out.println("Thread one is alive:  " + nrf.rt.isAlive());
         System.out.println("Thread two is alive:  " + nrs.rt.isAlive());
         System.out.println("Thread three is alive:  " + nrt.rt.isAlive());
         System.out.println("Main thread exiting.");
       }
   }


class JoinMe implements Runnable  //create a new thread class
  {
    Thread rt;
    String name;

    
   JoinMe(String threadname)
      {
        name = threadname;
        rt = new Thread(this, name);
        System.out.println( "Child thread: " + rt);
        rt.start();
      }

    // once a thread is started this is the entry point for subsequent time slices
    public void run()
      {
       
       try
            {
              for(int i=5; i>0; i--)
                 {
                   System.out.println(name+":  " + i);
                   rt.sleep(1000);
                 }
             }
         catch(InterruptedException e)
             {
               System.out.println("Child thread interrupted.");
             }
         System.out.println("exiting Child thread  " + name);
       }
}