Core java tutorial for beginners
A tutorial blog which explains different core concepts related to Java along with programming examples

February 17, 2016 Categories: Multithreading. No Comments on Daemon Threads

In this article we will learn what are daemon threads? and how to make thread as daemon thread along with example Java program.

 

A daemon thread is a thread which runs in the background. Example for daemon thread in Java is the garbage collector. In Java, thread can be divided into two categories:

  1. User threads
  2. Daemon threads

 

A user thread is a general thread which is created by the user. A daemon thread is also a user thread which is made as a daemon thread (background thread).

 

Difference between a user thread and a daemon thread is, a Java program will not terminate if there is at least one user thread in execution. But, a Java program can terminate if there are one or more daemon threads in execution.

 

To work with daemon threads, Java provides two methods:

void setDaemon(boolean flag)

boolean isDaemon()

 

TheĀ setDaemon() method is used to convert a user thread into a daemon thread. TheĀ isDaemon() thread can be used to know whether a thread is a daemon thread or not.

 

Below program demonstrates a daemon thread:

 

Output of the above program is:

This thread is a daemon thread: true

Daemon Thread: Hi

Daemon Thread: Hi

Daemon Thread: Hi

Daemon Thread: Hi

 

Note: Do you have a question on this article or have a suggestion to make this article better? You can ask or suggest us by filling in the below form. After commenting, your comment will be held for moderation and will be published in 24-48 hrs.

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll Up
Thank you for visiting startertutorials.com! If you like this website do share with your friends by clicking on the social icons available on the left hand side.

As the domain name is quite large to remember, use this short domain to visit this site. Short domain: stuts.me