How join method works in Java.
join() method is used for waiting the thread in execution until the thread on which join is called is not completed.
Remember, the thread which will wait is the thread in execution and it will wait until the thread on which join method called is not completed.
Consider a scenario below and we will try to understand join() method by going through example.
main acquired a lock on thread1
thread1 acquired a lock on thread1 //after 1 second this line is printed
thread1 completed //after 5 second this line is printed
main completed
In above example, we created 2 Threads,
Above task are executed inside native thread call, so it wont be visible in java thread API.
Remember, the thread which will wait is the thread in execution and it will wait until the thread on which join method called is not completed.
How join method works internally.
Consider a scenario below and we will try to understand join() method by going through example.
package javabypatel; public class ThreadJoinDemo extends Thread{ static ThreadJoinDemo thread1; public void run(){ try{ synchronized(thread1){ System.out.println(Thread.currentThread().getName()+" acquired a lock on thread1"); Thread.sleep(5000); System.out.println(Thread.currentThread().getName()+" completed"); } } catch (InterruptedException e){ } } public static void main(String[] ar) throws Exception{ thread1 = new ThreadJoinDemo(); thread1.setName("thread1"); thread1.start(); synchronized(thread1){ System.out.println(Thread.currentThread().getName()+" acquired a lock on thread1"); Thread.sleep(1000); thread1.join(); System.out.println(Thread.currentThread().getName()+" completed"); } } }Output:
main acquired a lock on thread1
thread1 acquired a lock on thread1 //after 1 second this line is printed
thread1 completed //after 5 second this line is printed
main completed
In above example, we created 2 Threads,
- "main" thread
- "thread1" thread
Who call notify/notifyAll in case of thread waiting on join method?
After run() method of thread is completed, it doesn't mean thread task is completed, It has to do many other tasks like- Destroying the associated stack,
- Setting the necessary threadStatus etc.
Above task are executed inside native thread call, so it wont be visible in java thread API.
You may also like to see
Advanced Java Multithreading Interview Question-Answer.
Exception Handling Interview Question-Answer
Method Overloading - Method Hiding Interview Question-Answer
Type Casting Interview Questions In Java
How is ambiguous overloaded method call resolved in java
Method Overriding rules in Java
Interface interview questions and answers in Java
Enjoy !!!!
If you find any issue in post or face any error while implementing, Please comment.
No comments:
Post a Comment