Daemon Threads:
Generally speaking, daemon threads are for background tasks, and non-daemon (user-threads) threads are for foreground tasks. The only difference is that JVM shuts down when the last non-daemon Thread terminates.
More often than not, background tasks run at a lower priority than foreground tasks (e.g. garbage collection). Still, many background tasks run at a higher priority (tracking the mouse etc.).
When an application starts, the main Thread (the Thread that calls the application's "main" method) is the only non-daemon Thread. When the application's main method exits, the main Thread terminates. If no other non-daemon threads are running, the application exits.
Servers typically have a non-daemon thread listening for client connections and then use non-daemon threads for processing client requests. When the last client request thread closes, the connection listener thread is terminated to shut the server down.
How to create a Daemon Thread:
This is an example is to demonstrate the usage of the setDaemon() and isDaemon() method.
public class DaemonThreadExample1 extends Thread{ public void run(){ // To check if method is Daemon or not: if(Thread.currentThread().isDaemon()){ System.out.println("Daemon thread executing"); } else{ System.out.println("user thread executing"); } } public static void main(String[] args){ //Creating 2 Threads DaemonThreadExample1 threadOne=new DaemonThreadExample1(); DaemonThreadExample1 threadTwo=new DaemonThreadExample1(); //Making user Thread t1 to Daemon threadOne.setDaemon(true); //starting both Threads threadOne.start(); threadTwo.start(); } }
Output:
Daemon thread executing user thread executing