'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)
Solution 1:[1]
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.
Solution 2:[2]
James is correct (+1 from me), I'm just trying to make this more explicit. Here is what happens:
Your main thread constructs the startinginconstructor
constructor.
The constructor calls start, which will result in the startinginconstructor object having its run method in the new thread.
After that the main thread will proceed to call makeitso. In makeitso this
is the startinginconstructor object, so the result is that the main thread waits until the thread represented by the startinginconstructor object has finished.
Java objects can be called by any thread, just because an object extends Thread doesn't mean any invocation of that method is happening on that thread.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Solomon Slow |
Solution 2 | путин Ð½ÐµÐºÑƒÐ»ÑŒÑ‚ÑƒÑ€Ð½Ð°Ñ ÑÐ²Ð¸Ð½ÑŒÑ |