java | thread join and isalive method

//Example  Use of isalive() and join() method
// join(): guranteed  that main thread terminates at last

class NewThread implements Runnable

{
String name;
Thread t;
NewThread(String n)
{

name=n;

t=new Thread(this,n);
System.out.println("thread name = "+t);
t.start();// start() calls run() method
}

public void run()//overrided method
{
try{

for(int i=0;i<=5;i++)
{
System.out.println(name +" i= "+i);
Thread.sleep(1000);//suspended for 2 seconds
}
}
catch(InterruptedException e)
{

System.out.println("child Thread interrupted ");
}
System.out.println(name+"Thread Exitting ");
}
}





class ThreadDemo
{

public static void  main(String ar[])//main is a thread which start very first
{
// creating three threads


Thread T =Thread.currentThread();   //T is object main thread


NewThread ob1=new NewThread("one");
NewThread ob2=new NewThread("two");
NewThread ob3=new NewThread("three");



System.out.println("Thread one is alive= "+ob1.t.isAlive());
System.out.println("Thread two is alive= "+ob2.t.isAlive());
System.out.println("Thread three is alive= "+ob3.t.isAlive());


//waiting for thread to be completed

try{
System.out.println("Waiting for threads to be finished");

ob1.t.join();
ob2.t.join();
ob3.t.join();

}
catch(InterruptedException e)
{



}

System.out.println("Thread one is alive= "+ob1.t.isAlive());
System.out.println("Thread two is alive= "+ob2.t.isAlive());
System.out.println("Thread three is alive= "+ob3.t.isAlive());
System.out.println("Main() Thread  is alive= "+T.isAlive());


System.out.println("Main Thread Exitting ");
}

}

Reactions:

0 comments:

Post a Comment