Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can child threads still execute even after that their parent thread die or terminate?

Here are my two classes:

public class Firstclass {
    public static void main(String args[]) throws InterruptedException {
        System.out.println("Main start....");
        Secondclass t1 = new Secondclass();
        t1.setName("First Thread");
        Secondclass t2 = new Secondclass();
        t2.setName("Second Thread");
        t1.start();
        t2.start();
        System.out.println("Main close...");
    }
}

and

public class Secondclass extends Thread {
    @Override
    public void run() {
        try {
            loop();
        } catch(Exception e) {
            System.out.println("exception is" + e);
        }
    }

    public void loop() throws InterruptedException {
        for(int i = 0; i <= 10; i++) {
            Thread t = Thread.currentThread();
            String threadname = t.getName();
            if(threadname.equals("First Thread")) {
                Thread.sleep(1000);
            } else {
                Thread.sleep(1500);
            }
            System.out.println("i==" + i);   
        }   
    }    
}

Now when I run Firstclass then the output is:

Main start....
Main close...
i==0
i==0
i==1
i==1
i==2
i==3
i==2
i==4
i==3
i==5
i==6
i==4
i==7
i==5
i==8
i==9
i==6
i==10
i==7
i==8
i==9
i==10

My question is: Let's consider main method is executed by a thread 'T' in JVM and t1 and t2 are obviously child threads of parent thread T so when T thread that is the main method dies how can T1 and T2 still execute and give us output. Because if parent thread dies or terminates then child thread should also die or terminate.

like image 450
TruePS Avatar asked Mar 04 '14 05:03

TruePS


2 Answers

There is no notion of a parent-child relationship between threads. Once the two threads are running they're basically peers. The main thread can exit while other thread still running.

Java has no real concept of "child" threads. When you start a thread it inherits the daemon and priority from the "parent" but that's the end of the parent/child relationship.

like image 124
Abimaran Kugathasan Avatar answered Oct 30 '22 19:10

Abimaran Kugathasan


Java does not know the concept of child threads. The three of your threads are treated equally. What comes next to your thinking is the creation of daemon threads, that are terminated when the last java non daemon thread is stopped.

The paper you posted is about a learning system called ThreadMentor. But this system behaves different from Java, this is not about Java.

Here could be a good start about Javas threading model:

http://docs.oracle.com/javase/tutorial/essential/concurrency/

like image 33
wumpz Avatar answered Oct 30 '22 19:10

wumpz