See my code in with link. My understanding with join concept is that if I created a thread "t2" in main thread. And I am writing like t2.join(). Than first all things under run method of t object will be executed than execution of main thread will be started back. But if I have created one more thread "t1" in main thread before "t2". At that time "t2"'s execution should be done first and than "t1"'s. Correct? But if you see in my linked code. t1 and t2 runs simultaneously. Why is it so?
-
5Don't link code. Include the relevant part in your question. – Kayaman Sep 05 '16 at 17:57
-
Haven't looked at your code, but if you start two threads (which will then run in parallel, that *is* the point of threads), and you then wait for thread 2 to complete using `join()`, then your main thread will continue when thread 2 ends, regardless of what thread 1 is doing. Thread 1 could end before or after thread 2, doesn't matter. – Andreas Sep 05 '16 at 18:00
-
@ketan I have posted my answer http://stackoverflow.com/a/39335699/504133 , hope it is helpful for you – nits.kk Apr 03 '17 at 13:59
2 Answers
As per the link you have shared
e1.start();
e2.start();
try {
e2.join();
} catch (InterruptedException e) {
e.printStackTrace();
Here we have 3 threads running
Main Thread
e1
e2.
Now when you write e2.join()
lets try to answer which thread will execute this statement ? Its the main Thread
(this statement is not being called from run()
method of any thread, it directly is under the execution of main Thread ), hence it is the main Thread
waiting for the completion of thread e2
. Thread e1
is already started so it runs without being affected.

- 5,204
- 4
- 33
- 55
Here in your programme main thread tells thread scheduler to start e1 by calling e1.start() now main thread e1 progress, similarly when e2.start() is called scheduler starts it in desperate path of execution like e1 & main thread continues. But when main thread executes e2.join() JVM causes main thread to wait until thread e2 completes its task. & Main thread will not execute remaining code, it will not ask thread scheduler to start e3, e4 & e5. Thanks happy learning.

- 1
- 1