viru viru - 5 months ago 22
Java Question

what happens if thread calls join() on itself

From what i read here Thread join on itself ;

When join method is called on itself, it should wait forever

I am currently preparing for ocajp 8 certification,for which going through dumps and when i got this question ,what i thought is main should wait forever

public class startinginconstructor extends Thread
{
private int x=2;
startinginconstructor()
{
start();
}
public static void main(String[] args) throws Exception
{
new startinginconstructor().makeitso();
}
public void makeitso() throws Exception
{
x=x-1;
System.out.println(Thread.currentThread().getName()+" about to call join ");
join();
System.out.println(Thread.currentThread().getName()+" makeitso completed ");

// above line shouldn't be executed (method shouldn't be completed as well )since it joined on itself..?

}
public void run()
{
System.out.println(Thread.currentThread().getName()+" run started ");
x*=2;
System.out.println(Thread.currentThread().getName()+" run about to complete ");
}
}


program ended with following output

main about to call join
Thread-0 run started
Thread-0 run about to complete
main makeitso completed


Did i wrongly get the meaning of thread waiting forever or is there something i am missing


note: I know starting thread from constructor is not a recommended practice.. this is exact question in the dumps so i just pasted it (* not pretty much exact actually,i have placed println statements to see flow of the program)

Answer

There is no thread that joins itself in your example.

The main() thread in your example creates a new thread and then it joins the new thread.

Don't confuse Thread (i.e., the java object) with thread (the execution of the code.) All of your methods belong to the same Thread object, but they run in two different threads.