# Create a Daemon in Java (with example)

In 
Published 2022-12-03

This tutorial will explain to you how we can create a daemon process in Java. This article will show you an example as well.

Multithreading refers to two or more tasks executing concurrently within a single process. A thread is an independent path of execution within a process. Many threads can run concurrently within a process. There can be multiple processes inside the OS.

NOTES:

  • Cost of communication between the threads is low.
  • Threads share the same address space and therefore can share both data and code
  • Threads allow different tasks to be performed concurrently

There are two ways for creating thread in java:

  1. by extending the Thread class (java.lang.Thread)
  2. by implementing the Runnable interface (java.lang.Runnable)

Daemon threads are Low Priority threads. A thread that executes main logic of the project is called non-daemon thread. Every user defined thread is created as non-daemon thread by default, because main thread is a non-daemon thread. Here is an example of creating daemons in Java using the "extends Thread" method (the "implements Runnable" method is similar):

package threads.java.example;
 
class PrintValues {
 
    static void printValues(String threadName){
         
        for (int i = 1; i < 12; i++) {
             System.out.println("printValues   --->   "  + i + " >>> FROM : "+threadName);
        }
   }
}
package threads.java.example;
 
public class ThreadDaemonClass extends Thread {
       private Thread thread;
       private String threadName;
        
       ThreadDaemonClass( String name) {
          threadName = name;
          System.out.println("Creating " +  threadName );
       }
        
       public void run() {
          System.out.println(threadName + " is running ...");
         
          PrintValues.printValues(threadName);
           
          System.out.println( threadName + " has been finished.");
       }
        
       public void start () {
          System.out.println("Start " +  threadName );
          if (thread == null) {
              thread = new Thread (this, threadName);
               
              // Sets the Thread as "daemon"
              thread.setDaemon(true);
              thread.start ();
          }
       }
    }
package threads.java.example;
 
public class ThreadsInJavaExample {
 
       public static void main(String args[]) {
          ThreadDaemonClass T1 = new ThreadDaemonClass("Thread A");
          T1.start();
 
          ThreadDaemonClass T2 = new ThreadDaemonClass("Thread B");
          T2.start();
       }   
    }