Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Thread inside thread: what happens if parent thread is killed? [duplicate]

There is something I can't understand with threads in general. In my case, using Java and Android.

Let's say I have a Thread named A, which launches thread B. If thread A stops, then thread B will continue to live. How is this possible? Who belongs to the Thread B now? To the main thread?

Thread class

public class ParentThread extends Thread {

    public void run(){
        Log.e("PARENT THREAD", "STARTS RUNNING");
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    Log.e("CHILD THREAD", "IS ALIVE");
                    try {
                        Thread.sleep(1000);
                    }
                    catch (InterruptedException exc) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();
        Log.e("PARENT THREAD", "STOPS RUNNING");
    }
}

Activity

new ParentThread().start();

Logcat output

01-07 13:45:16.726 22063-22081/? E/PARENT THREAD: STARTS RUNNING
01-07 13:45:16.726 22063-22081/? E/PARENT THREAD: STOPS RUNNING
01-07 13:45:16.727 22063-22082/? E/CHILD THREAD: IS ALIVE
01-07 13:45:17.727 22063-22082/? E/CHILD THREAD: IS ALIVE
01-07 13:45:18.727 22063-22082/? E/CHILD THREAD: IS ALIVE
01-07 13:45:19.727 22063-22082/? E/CHILD THREAD: IS ALIVE
...
like image 216
Scaraux Avatar asked Jan 06 '23 21:01

Scaraux


1 Answers

From docs Thread

A Thread is a concurrent unit of execution. It has its own call stack for methods being invoked, their arguments and local variables. Each application has at least one thread running when it is started, the main thread, in the main ThreadGroup. The runtime keeps its own threads in the system thread group.

like image 180
gio Avatar answered Feb 04 '23 10:02

gio