threads
Application exits when all daemon threads exit
In this example we shall show you how to create a daemon thread in order to force an application to exit. We have created a class, MyDaemonThread
that extends the Thread and overrides its run()
method. In short:
- In its
run()
method the thread tests if it is a daemon thread, withisDaemon()
API method of Thread and sleeps for one second. - We create a new instance of
MydaemonThread
in amain()
method. We mark it as a daemon, usingsetDaemon(boolean on)
API method of Thread, and then the thread’s execution beggins, using itsstart()
API method. The Java Virtual Machine will exit when the only threads running are all daemon threads. Since the only thread running isMydaemonThread
, the application exits,
as described in the code snippet below.
package com.javacodegeeks.snippets.core; import java.util.logging.Level; import java.util.logging.Logger; public class DeamonThreadExit { public static void main(String[] argv) throws Exception { Thread t = new MyDaemonThread(); t.setDaemon(true); t.start(); } } class MyDaemonThread extends Thread { MyDaemonThread() { } @Override public void run() { boolean isDaemon = isDaemon(); System.out.println("isDaemon:" + isDaemon); try { Thread.sleep(1000); } catch (InterruptedException ex) { } } }
This was an example of how to create a daemon thread in order to force an application to exit in Java.