4

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
...
MC Emperor
  • 22,334
  • 15
  • 80
  • 130
Scaraux
  • 3,841
  • 4
  • 40
  • 80

2 Answers2

5

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.

gio
  • 4,950
  • 3
  • 32
  • 46
4

Let's say I have a Thread named A, that launches a Thread B. If the Thread A stops, the Thread B will continue to live. How is this possible?

It's easily possible - there's nothing that makes thread B stop, so it doesn't stop.

Who belongs to the Thread B now? To the main thread?

Threads don't belong to each other. The fact that it was Thread A that launched Thread B isn't recorded anywhere - as far as the system is concerned, you have two threads with no relationship between them whatsoever.

gio
  • 4,950
  • 3
  • 32
  • 46
user253751
  • 57,427
  • 7
  • 48
  • 90