2

I came to know in Java that: children threads won't outlive the main thread, but, seemingly, the behavior of this application shows different results.

The child thread keeps working while the main one has done working!

Here is what I do:

public class Main {

public static void main(String[] args) {

    Thread t = Thread.currentThread();

    // Starting a new child thread here
    new NewThread();

    try {
        Thread.sleep(1000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

    System.out.println("\n This is the last thing in the main Thread!");


    }
}

class NewThread implements Runnable {

private Thread t;

NewThread(){
    t= new Thread(this,"My New Thread");
    t.start();
}

public void run(){
    for (int i = 0; i <40; i++) {
        try {
            Thread.sleep(4000);
            System.out.printf("Second thread printout!\n");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

}

What do I fail to understand here … Or that's a new feature in Java starting from JDK 9?

securecurve
  • 5,589
  • 5
  • 45
  • 80

1 Answers1

6

According to the documentation of Thread#setDaemon:

The Java Virtual Machine exits when the only threads running are all daemon threads.

Your child thread is not a daemon thread, so the JVM does not exit even though the main thread no longer runs. If you call t.setDaemon(true); in the constructor of NewThread, then the JVM will exit after the main thread has finished executing.

Jacob G.
  • 28,856
  • 5
  • 62
  • 116
  • 4
    I would also add to the (correct) answer the fact that a JVM thread does not really have a concept of "parent". The "parent" thread can finish and be its memory can be reclaimed while the "child" can continue running. – Paweł Motyl Mar 31 '18 at 18:38
  • 3
    Daemon threads have a ton of problems on Windows; basically, they don't work. – Abhijit Sarkar Mar 31 '18 at 19:30