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);
}
}
}
Quickly Find What You Are Looking For
OnlineTpoint is a website that is meant to offer basic knowledge, practice and learning materials. Though all the examples have been tested and verified, we cannot ensure the correctness or completeness of all the information on our website. All contents published on this website are subject to copyright and are owned by OnlineTpoint. By using this website, you agree that you have read and understood our Terms of Use, Cookie Policy and Privacy Policy.
point.com