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.
See more on this question at Stackoverflow