Menu Bar

Drop Down MenusCSS Drop Down MenuPure CSS Dropdown Menu

Saturday, 26 November 2016

Using isAlive() and join() Methods In Java ?

Previously we have discussed about

There are two ways to determine whether a thread has finished its execution or not. First method is isAlive() and second is join() method.

isAlive() : 
The general form is isAlive() method is : public final boolean isAlive()
This method returns true if the thread upon which it is called is still running.Otherwise it returns false.

Example of isAlive():

public class IsAliveExample extends Thread {

public void run(){
System.out.println("IN run method : ");
try {
Thread.sleep(1000);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("OUT run method : ");
}
public static void main(String[] args) {
IsAliveExample t1 = new IsAliveExample();
IsAliveExample t2 = new IsAliveExample();
t1.start();
t2.start();
System.out.println("T1 Status : "+t1.isAlive());
System.out.println("T2 Status : "+t2.isAlive());
}

}
Program Output:
IN run
IN run
T1 Status : true
T2 Status : true
OUT Run
OUT Run

join() :
The general form of join() method is : 
public final void join() throws InterruptedException

The join() method is used more commonly than isAlive(), This method waits until the thread on which it is called terminates.
Using join() method, we tell our thread to wait until the specified thread completes its execution. 
In join() method we can also specify a maximum amount of time that you want to wait for specified thread to terminate.

Its Declaration form is :
final void join(long milliseconds) throws InterruptedException

Example of join():
In this program join() method ensure that Thread t1 finishes its processing before Thread t2 starts. 

public class JoinMethodExample extends Thread{
public void run(){
System.out.println("In Run");
try {
Thread.sleep(1000);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("Out Run");
}
public static void main(String[] args) {
JoinMethodExample t1 = new JoinMethodExample();
JoinMethodExample t2 = new JoinMethodExample();
t1.start();
try {
t1.join();
} catch (Exception e) {
e.printStackTrace();
}
t2.start();
}
}
Program Output:
In Run
Out Run
In Run
Out Run


      
Blog Author - Pushkar Khosla,
Software Developer by Profession with 3.0 Yrs of Experience , through this blog i'am sharing my industrial Java Knowledge to entire world. For any question or query any one can comment below or mail me at pushkar.itsitm52@gmail.com.

This blog is all about to learn Core Java ,Interview Programs and Coding tricks to polish your Java Knowledge. If you like the content of this blog please share this with your friends.



Share this Blog with yours Friends !!

No comments:

Post a Comment