I am trying to learn about the join()
method. In my code when I use DEBUG mode it first calls the run()
method, but when I run it my output differs. When we try to start a thread using start()
method, the run()
method will be called internally and it gets executed. But in my output it differs. Can anyone suggest me a solution?
class JoinExample extends Thread{
public void run(){
System.out.println("CurrentThread:"+
Thread.currentThread().getName());
System.out.println("Is Alive?"+
Thread.currentThread().isAlive());
}
public static void main(String args[]){
JoinExample t1=new JoinExample();
JoinExample t2=new JoinExample();
JoinExample t3=new JoinExample();
t1.start();
System.out.println("Is Alive?" +
t1.isAlive());
t2.start();
t3.start();
}
}
My output when I use DEBUG mode:
Current Thread:Thread-0
Is Alive?true
Is Alive?false
Current Thread:Thread-1
Is Alive?true
Current Thread:Thread-2
Is Alive?true
My output when I run my code:
Is Alive?true
Current Thread:Thread-1
Is Alive?true
Current Thread:Thread-0
Current Thread:Thread-2
Is Alive?true
Is Alive?true
The executing order of any thread is not determinist, that means that it will always vary from execution to execution, and it is impossible to know the order.
The DEBUG mode does not change anything.
If you want them to be executed in order, use the join method this way:
t1.start();
t1.join();
t2.start();
t2.join();
t3.start();
t3.join();
This way the code will wait for thread number 1 to finish, and then it will start thead number 2, and so on.