How To Create Daemon Thread In Java

Introduction

In this article we discuss how to create a Daemon thread in Java.

Daemon Thread in Java

Basically there are two types of threads in Java, a daemon thread and a user thread. The daemon thread is a service provider thread. It provides services to the user thread. Its life depends on the user threads, in other words when all the user threads die, the JVM terminates this thread automatically.

Some points to remember about Daemon Thread

  • A Daemon Thread provides services to a user thread for background supporting tasks. It has no other role in life than to server user threads.
  • Its life depends on user threads.
  • It is a low priority thread.

Why the JVM stops the daemon thread if there is no user thread remaining

The basic purpose of a daemon thread is to provide services to a user thread for background support purposes. If there is no user thread then there is no reason for the JVM to keep running this thread. That is why the JVM stops the daemon thread if there is no user thread.

Methods for daemon thread

boolean isDaemon()
    Determines whether the current thread is a Daemon thread.

void setDaemon(boolean status)
    Marks the current thread as a daemon thread or user thread.

Example

class DaemonThreadEx extends Thread

  {

    public void run()

      {

        System.out.println("Name Of Thread: "+ Thread.currentThread().getName());

        System.out.println("Daemon Thread: "+ Thread.currentThread().isDaemon());

      }

    public static void main(String[] args)

      {

        DaemonThreadEx th1=new DaemonThreadEx();

        DaemonThreadEx th2=new DaemonThreadEx();

        th1.setDaemon(true);

        th1.start();

        th2.start();

      }

  }

Output

Fig-1.jpg

Note

If we need to make a user thread a Daemon then the thread must not be started otherwise it will throw IllegalThreadException.

class DaemonThreadEx1 extends Thread

{

public void run()

{

System.out.println("Name Of Thread: "+ Thread.currentThread().getName());

System.out.println("Daemon Thread: " + Thread.currentThread().isDaemon());

}

public static void main(String[] args)

{

DaemonThreadEx1 th1=new DaemonThreadEx1();

DaemonThreadEx1 th2=new DaemonThreadEx1();

th1.start();

th1.setDaemon(true);

th2.start();

}

}

Output

Fig-2.jpg

Up Next
    Ebook Download
    View all
    Learn
    View all