How Join() method works in Multithreaded environment:
Sometimes one thread needs to know when another thread is ending. In java, isAlive() and join() are two different methods to check whether a thread has finished its execution.
The isAlive() method returns true if the thread upon which it is called is still running otherwise it returns false.
Syntax: final boolean isAlive()
But, join() method is used more commonly than isAlive(). This method waits until the thread on which it is called terminates.
Syntax: final void join() throws InterruptedException
Using join() method, we tell our thread to wait until the specified thread completes its execution. There are overloaded versions of join() method, which allows us to specify time for which you want to wait for the specified thread to terminate.
Syntax: final void join(long milliseconds) throws InterruptedException
Example:
package com.core.alljavaconcepts.multithreading;
public class JoinExample {//Main class
public static void main(String[] args) {
Thread th1 = new Thread(new MyClass(), "Thread1");
Thread th2 = new Thread(new MyClass(), "Thread2");
//start first thread
th1.start();
//Start second thread once th1 is dead
try {
th1.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
//start second thread
//Display below message once the th2 is dead
try {
th2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Threads completed");
}
}
class MyClass implements Runnable{
@Override
public void run() {
Thread t = Thread.currentThread();
System.out.println(t.getName()+" Strated ");
try {
t.sleep(4000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(t.getName()+" Ended ");
System.out.println("------------------------");
}
}
As per above example, first the thread one th1 starts its execution, and once after it completes its execution only the second thread th2 will start exeuting and completes the execution and displayes the last statement.
Lets see the out put of the above example code:
That is as fallows:
Console out put:
Thread1 Strated
Thread1 Ended
------------------------
Thread2 Strated
Thread2 Ended
------------------------
Threads completed
You may also like the fallowing posts:
No comments:
Post a Comment