Daemon Thread in Java

Daemon Thread

There are two types of threads

  • User Threads
  • Daemon Threads

The threads created by the user(create a thread in the program ) are called user threads.

The threads that work in the background providing service to others are called Daemon Threads.

The two methods used only  in the daemon thread, not in the user thread are:

  • Public void setDaemon(Boolean value): sets a thread to be a daemon thread.
  • Public Boolean isDaemon(): checks if the given thread is a daemon.

Example of Daemon Thread in Java….

class threadtest implements Runnable

{

Thread t1,t2;

public threadtest()

{

t1=new Thread(this);

t1.start();

t2=new Thread(this);

t2.setDaemon(true);

}

public void run()

{

System.out.println(Thread.activeCount());

System.out.println(t1.isDaemon());

System.out.println(t2.isDaemon());

}

public static void main(String ass[])

{

new threadtest();

}

}

Daemon Thread in Java

Explanation…

We create two threads t1 and t2.

Set the t2 thread to be a daemon thread by using the setDaemon() method.

Daemon() is used to find whether the process of converting the user-defined thread has been successful or not (it’s working or not). This method returns true if the thread is a daemon if the thread is not a daemon then it gives false.

This program also prints the total number of threads that are running in a program (using activeCount()).