Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does a child thread in Java prevent the parent threads to terminate?

When I create and start a thread inside another thread, will it be a child thread? Does it prevent the termination of the parent thread while the child thread is running? For example:

new Thread(new Runnable() {
    @Override
    public void run() {
        //Do Sth
        new Thread(new Runnable() {
            @Override
            public void run() {
                //Do Sth
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        //Do Sth
                    }
                }).start();
                //Do Sth
            }
        }).start();
        //Do Sth
    }
    //Do Sth            
}).start();
like image 559
Johnny Avatar asked Nov 14 '13 20:11

Johnny


People also ask

Does child thread still execute even after if their parent thread dies or terminates?

Because if parent thread dies or terminates then child thread should also die or terminate. If you run those threads as daemon threads, when main thread finishes, your application will exit.

What happens to child threads when process exits?

If any thread calls exit , then all threads terminate.

What is child thread in Java?

The Main thread in Java is the one that begins executing when the program starts. All the child threads are spawned from the Main thread and it is the last thread to finish execution.

Can parent thread create child threads?

Thread CreationThe creating thread is the parent thread, and the created thread is a child thread. Note that any thread, including the main program which is run as a thread when it starts, can create child threads at any time.


Video Answer


1 Answers

In your code, there is a parent-child relationship between objects. However, there is no notion of a parent-child relationship between threads. Once the two threads are running they're basically peers.

Let's say that thread A starts thread B. Unless there's explicit synchronisation between them, either thread can terminate whenever it pleases without affecting the other thread.

Note that either thread can keep the process alive for as long as the thread lives. See What is Daemon thread in Java?

like image 104
NPE Avatar answered Oct 29 '22 11:10

NPE