A call to join() Guaranteed to cause the current thread to stop executing until the thread it joins with (in other words, the thread it calls join() on) completes.
However, in my program both the threads are executing simultaneously. Thread1 is not waiting for Thread2 to finish its execution.
What is wrong with my program?
public class Launcher1 {
public static void main(String[] args) {
JoinExample runnable=new JoinExample();
Thread thread1=new Thread(runnable);
Thread thread2=new Thread(runnable);
thread1.start();
try {
Thread.sleep(2000);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
thread2.start();
try {
thread2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public class JoinExample implements Runnable{
public void run(){
for(int i=0;i<10;i++){
System.out.println("i:"+i+" "+Thread.currentThread().getName());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
Output:
i:0 Thread-0
i:1 Thread-0
i:0 Thread-1
i:2 Thread-0
i:1 Thread-1
i:3 Thread-0
i:4 Thread-0
i:2 Thread-1
i:3 Thread-1
i:5 Thread-0
i:4 Thread-1
i:6 Thread-0
i:7 Thread-0
i:5 Thread-1
i:8 Thread-0
i:6 Thread-1
i:7 Thread-1
i:9 Thread-0
i:8 Thread-1
i:9 Thread-1
However, in my program both the threads are executing simultaneously. Thread1 is not waiting for Thread2 to finish its execution.
No, and it wouldn't - because thread 1 isn't calling join. Look at the docs you quoted again:
A call to join() Guaranteed to cause the current thread to stop executing until the thread it joins with
To put it another way: the join() method doesn't finish until the thread it's called on has finished.
You've got three threads in your program - two that are running JoinExample.run, and the "main" thread that starts the other two. You're telling that main thread to wait for thread 2 to finish, but that's all. Your two JoinExample threads are entirely independent.
There are three threads in question here.
1st thread - main thread, which runs the main method and spawns the 2 child threads.
2nd thread - thread1
3rd thread - thread2
When you say thread2.join(), the main thread will block until thread2 finishes,thread1 and thread2 will continue to run.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With