I have created two non-daemon threads which will terminate before the rest two daemon threads.
One non-daemon thread wait for 20 sec,
one daemon thread wait for 40 sec,
one non-daemon thread sleep for 15 sec,
one daemon thread sleep for 30 sec,
one daemon thread sleep for 10 sec. The idea to terminate non-daemon threads before some daemon ones.
As the result suggests, the JVM will terminate as soon as there is no non-daemon thread alive, without executing the rest statements in the Runnable tasks of the daemon threads, even if they are inside finally block without throwing InterruptedException.
public class DeamonTest {
public static void main(String[] args) {
spawn(40000, Action.wait, true);
spawn(30000, Action.sleep, true);
spawn(10000, Action.sleep, true);
spawn(20000, Action.wait, false);
spawn(15000, Action.sleep, false);
}
enum Action {
wait, sleep
}
private static void spawn(final long time, final Action action,
boolean daemon) {
final Thread thread = new Thread(new Runnable() {
@Override
public void run() {
Thread thread = Thread.currentThread();
try {
switch (action) {
case wait: {
synchronized (this) {
System.out.println(thread + " daemon="
+ thread.isDaemon() + ": waiting");
wait(time);
}
break;
}
case sleep: {
System.out.println(thread + " daemon="
+ thread.isDaemon() + ": sleeping");
Thread.sleep(time);
}
}
System.out.println(thread + " daemon=" + thread.isDaemon()
+ ": exiting");
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
System.out.println(thread + " daemon=" + thread.isDaemon()
+ ": finally exiting");
}
}
});
thread.setDaemon(daemon);
thread.start();
}
}