The class java.lang.Thread provides join() method which allows one thread to wait until another thread finishes its execution. If t is a thread object then on calling t.join() will cause the current thread to pause its execution until the thread it joined completes.
If there are multiple threads calling the join() method that means overloading on join allows the programmer to specify the waiting period. Like sleep, join also depends on the OS for timing, so we should not assume that join will wait exactly long as we specified.
If there are multiple threads calling the join() method that means overloading on join allows the programmer to specify the waiting period. Like sleep, join also depends on the OS for timing, so we should not assume that join will wait exactly long as we specified.
join() method
There are three overloaded join methods -
- join() - It will put the current thread on wait until the thread on which it is called is done executing. This will throw InterruptedException if the thread is interrupted.
- join(long millis) - It will put the current thread on wait for the specified time or until the time the thread on which it is called is done executing (whichever is earlier).
- join(long millis, int nanos) - It is similar to above but it waits for the time (millis + nanos)
Following example explains the concept -
In the above example we can see clearly second thread t2 starts after first thread t1 has died and t3 will start its execution after second thread t2 has died.
The output of the above program will be -
Current Thread: main
Current Thread: Thread-0
0
Current Thread: Thread-0
1
Current Thread: Thread-0
2
Current Thread: main
Current Thread: Thread-1
0
Current Thread: Thread-1
1
Current Thread: Thread-1
2
Current Thread: Thread-2
0
Current Thread: Thread-2
1
Current Thread: Thread-2
2
Conclusion
Congratulations!! 🙋 today we discussed the concepts of join() method and its sample implementation. I hope you enjoyed this post.
You can find the complete code of this project on my GitHub in this commit. Feel free to fork or open issues, if any.
I would love to hear your thoughts on this and would like have suggestions from you to make it better.
Happy Coding 😊
The output of the above program will be -
Current Thread: main
Current Thread: Thread-0
0
Current Thread: Thread-0
1
Current Thread: Thread-0
2
Current Thread: main
Current Thread: Thread-1
0
Current Thread: Thread-1
1
Current Thread: Thread-1
2
Current Thread: Thread-2
0
Current Thread: Thread-2
1
Current Thread: Thread-2
2
Conclusion
Congratulations!! 🙋 today we discussed the concepts of join() method and its sample implementation. I hope you enjoyed this post.
You can find the complete code of this project on my GitHub in this commit. Feel free to fork or open issues, if any.
I would love to hear your thoughts on this and would like have suggestions from you to make it better.
Happy Coding 😊
Comments
Post a Comment