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();
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.
If any thread calls exit , then all threads terminate.
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.
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.
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With