If a Thread wants to wait until the completion of some other Thread, then we can use the Join method. for example if Thread t1 want to waits until completion of Thread t2 then Thread t1 has to call t2.join()
, if t1 executes t2.join
then immediately t1 will be entered into wait state , once Thread t2 completes its execution , after then t1 will continue its execution
public class JoinMethod extends Thread{
@Override
public void run() {
for(int i=0;i<5;i++){
System.out.println("Custom Thread");
}
try{
Thread.sleep(2000);
} catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
class TheCodeData{
public static void main(String[] args) throws InterruptedException {
JoinMethod t = new JoinMethod();
t.start();
t.join();
for(int i =0;i<5;i++){
System.out.println("Main Thread");
}
}
}
In the above Example main thread calls join()
method on Child thread object hence main thread will wait unitll completion of child thread.
Similar Java Tutorials
- Odd Even in Java
- Fibonacci Series Java
- Method to print exception information in Java
- Exception Handling by Using try-catch in Java
- Checked Exception vs Unchecked Exception
- Exception Hierarchy in Java
- Java Exception Handling Interview Questions
- final finally finalize in java
- User Defined Exception in Java
- Exception Handling Keyword in Java
- throw throws in Java
- try with multiple catch block in Java
- Threads in Java
- Thread priority in Java