Java Join() & isAlive() method


The join() method is used to wait for a thread to terminate.


Syntax:

 final void join( ) throws InterruptedException

The isAlive() method returns true if the thread is still running otherwise it returns false.


Syntax:

 final boolean isAlive( )

Example

By extending Thread class

public class Joinmethod extends Thread{  
    public void run(){  
        try{  
            for(int i=1;i<=5;i++){ 
                 System.out.println(i); 
                 Thread.sleep(700); 
            }  
        }catch(InterruptedException e){
            System.out.println(e);
        }  
    }  
    public static void main(String args[]){  
        Joinmethod t1=new Joinmethod();  
        Joinmethod t2=new Joinmethod();  
        Joinmethod t3=new Joinmethod();  
        t1.start();  
        System.out.println("Thread One is alive: "+ t1.isAlive());
        try{  
            t1.join(); 
        }catch(InterruptedException e){
            System.out.println(e);
        }  
        t2.start();  
        t3.start(); 
    }  
} 

Example

By implementing the Runnable interface.

class Joinmethod implements Runnable {  
    String name; // name of thread
    Thread t;
    Joinmethod(String threadname) {
        name = threadname;
        t = new Thread(this, name);
        System.out.println("New thread: " + t);
        t.start(); // Start the thread
    }
    public void run(){  
        try{  
            for(int i=1;i<=5;i++){ 
                 System.out.println(i); 
                 Thread.sleep(700); 
            }  
        }catch(InterruptedException e){
            System.out.println(e);
        }  
        System.out.println(name + " exiting.");
    }
}
public class Joinmethod1
{
    public static void main(String args[]){  
        Joinmethod t1=new Joinmethod("One");  
        Joinmethod t2=new Joinmethod("Two");  
        Joinmethod t3=new Joinmethod("Three");  
        System.out.println("Thread One is alive: "+ t1.t.isAlive());
        System.out.println("Thread Two is alive: "+ t2.t.isAlive());
        System.out.println("Thread Three is alive: "+ t3.t.isAlive());
        try{  
            System.out.println("Waiting for threads to finish.");
            t1.t.join();
            t2.t.join();
            t3.t.join();
        }catch(InterruptedException e){
            System.out.println(e);
        }  
    }  
} 



Onlinetpoint is optimized for basic learning, practice and more. Examples are well checked and working examples available on this website but we can't give assurity for 100% correctness of all the content. This site under copyright content belongs to Onlinetpoint. You agree to have read and accepted our terms of use, cookie and privacy policy.