I am confused uisng joins method in Threads
Could somebody please explain
I have read that the Parent Thread would wait for its
child Thread , until the child completes its operation
I have a Parent Thread as shown :
public class join implements Runnable {
public void run() {
System.out.println("Hi");
}
public static void main(String[] args) throws Exception {
join j1 = new join();
Thread parent = new Thread(j1);
child c = new child();
Thread child = new Thread(c);
parent.start();
child.start();
parent.join();
}
}
Child Thread :
public class child implements Runnable {
public void run() {
try {
Thread.currentThread().sleep(100000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("i m child");
}
}
Upon executing this , the output is
Hi
i m child
As per my understanding it should be in the reverse order
i m child
Hi
Please correct me if i am wrong
In your case you have three threads: main, parent and child. Main is the initial thread that is always created by the jvm to run your program. Parent and child are two threads that have been created in main. Your labeling of one thread as parent is a misnomer. It is the parent of no other threads. Rather it is the child of main. Join is intended so that one thread may wait for another to finish execution, before it continues.
A hypothetical example might be between a waiter and a chef. That is, a waiter cannot serve food until the chef has cooked it. So the waiter must needs to wait for (join) the chef to finish before serving the food.