I am in doubt, what happens when a thread joins itself. i.e thread calls the join method on its own. I am not getting any error.
Sample :
public class JoinItself extends Thread {
public void run() {
System.out.println("Inside the run method ");
System.out.println(Thread.currentThread().isAlive());
for(int i=0;i<5;i++) {
try {
System.out.println("Joining itself ...");
Thread.currentThread().join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
JoinItself j = new JoinItself();
System.out.println(j.isAlive());
j.start();
System.out.println(j.isAlive());
System.out.println("Thread started ...");
}
}
But Why? Should I get any error?
The concept of a thread joining itself does not make sense.
It happens out that the
join()method uses theisAlive()method todetermine when to return from the
join()method. In the current implementation, it alsodoes not check to see if the thread is joining itself.
In other words, the
join()method returns when and only when the thread is no longer alive. This will have the effect ofwaiting forever.