I read some tutorials and even already asked question here
But I am confused again with join method. What I know Java cannot guarantee the order of execution of threads under normal circumstances.
what i read using join() ,it makes sure that as soon as a thread calls join,the current thread will not execute unless the thread you have called join is finished.
My example which I tried
public class ThreadTest1 extends Thread{
@Override
public void run() {
super.run();
for(int i=0; i<10; i++)
{
System.out.println(i + " :"+ Thread.currentThread().getName());
}
}
public static void main(String[] args) {
System.out.println("Thread is getting started");
ThreadTest1 th0= new ThreadTest1();
th0.start();
ThreadTest1 th1= new ThreadTest1();
th1.start();
try {
th1.join(10000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Outputs:
First time output
0 :Thread-1
1 :Thread-1
2 :Thread-1
0 :Thread-0
3 :Thread-1
1 :Thread-0
4 :Thread-1
2 :Thread-0
5 :Thread-1
3 :Thread-0
6 :Thread-1
4 :Thread-0
7 :Thread-1
8 :Thread-1
9 :Thread-1
5 :Thread-0
6 :Thread-0
7 :Thread-0
8 :Thread-0
9 :Thread-0
Second time output:
0 :Thread-1
0 :Thread-0
1 :Thread-1
1 :Thread-0
2 :Thread-1
2 :Thread-0
3 :Thread-1
3 :Thread-0
4 :Thread-1
4 :Thread-0
5 :Thread-1
5 :Thread-0
6 :Thread-1
6 :Thread-0
7 :Thread-1
7 :Thread-0
8 :Thread-1
8 :Thread-0
9 :Thread-1
9 :Thread-0
Why both outputs are different.
I used join() with th1 object. when th0 is running and jvm found th1 thread So thread-1 should be finished first then Thread-0.
Why its is printing Thread-1, Thread-0 without any sequence. If outputs will be like this then what is the use of join() methd?
Can anyone please explain with my outputs.