What is a child thread

1. In the most common case, a subthread is started in the main thread, after which the main thread and subthread do not mutually affect the life cycle, ie the main thread ends and the subthread can continue to be executed. It can continue to run.

The test code is as follows:

The results are as follows:

The main thread begins. . . .
The main thread ends. . . .
The child thread is started. . . .
The child thread ends. . . .

2. The main thread starts the child thread, but the main thread ends and the child thread also ends.

The code is as follows:

The results are as follows:

The main thread begins. . . .
The main thread ends. . . .
The child thread is started. . . .
The grandson thread begins. . . .
The child thread ends. . . .

Note: The Thread.setDaemon (true) method is used here to set the ThirdThread thread as the daemon thread of the ChildThread thread. As soon as the child thread thread ends, the third thread thread ends. It cannot be set as a daemon thread for a running thread, otherwise a java.lang.IllegalThreadStateException will be thrown.

3. The main thread has a child thread open. The main thread must wait for the child thread to finish before exiting the main thread.

The test code is as follows:

Test results:

The main thread begins. . . .
The child thread is started. . . .
The child thread ends. . . .
The main thread ends. . . .

Note: The join () method is used here to make the main thread wait for the child thread to complete, and then the main thread continues execution. Here the join () method must be called after the child thread has started.

The process is the basic unit of resource allocation and the thread is the basic unit of CPU scheduling. For the CPU, there is actually no difference between the main thread and the subordinate threads, both are one thread. The resources of the process are shared among the threads under the process. As long as the process is still running, the thread can run normally, that is, the thread is dependent on the process and there is no dependency relationship between the thread and the thread. Does not affect other threads. However, the above changes the relationship between the main thread and the child thread by calling the interfaces provided by the JVM such as setDaemon and join. This should be the JVM interface code doing the processing that disrupts the thread's lifecycle.

Daemon threads are essentially the same as non-daemon threads. However, if the remaining threads in the virtual machine are only daemon threads, the virtual machine will terminate. As long as there is no non-daemon thread in the virtual machine, the virtual machine will not terminate.