Hi all, will daemon thread stop working when the enclosing it thread will finish? Or daemon thread will stop when the "main" thread will finish?
I tested this example on jre6 and result was daemon thread stopped working when the enclosing it thread finished. Notice that java docs said that daemon threads are killed when no other application threads remain. And it's not said that daemon threads are killed when parent non-daemon thread remains.
Please give me answers. Please send me any material about this question. Sorry for my English.
public class Main {
public static void main(String[] args) {
Thread simple = new Thread(new SimpleTask());
simple.start();
}
}
class SimpleTask implements Runnable {
public void run() {
try {
Thread daemon = new Thread(new DaemonTask());
daemon.setDaemon(true);
daemon.start();
Thread.sleep(5000);
} catch (InterruptedException e) {}
};
}
class DaemonTask implements Runnable {
public void run() {
int i = 0;
while (true) {
try {
System.out.println("a" + (i++));
Thread.sleep(500);
} catch (InterruptedException e) {}
}
}
}
will daemon thread stop working when the enclosing it thread will finish?
There's no such concept as an "enclosing thread" in Java. There are thread groups but they're rarely used.
Daemon threads are simply threads which don't stop the JVM from terminating. When there aren't any non-daemon threads left, the JVM will terminate. If there are still some non-daemon threads executing, the JVM will keep going, including any daemon threads - whether or not the threads that started those daemon threads have finished.
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