Trusted answers to developer questions

What is Thread.isDaemon() function in Java?

Get Started With Machine Learning

Learn the fundamentals of Machine Learning with this free course. Future-proof your career by adding ML skills to your toolkit — or prepare to land a job in AI or Data Science.

Overview

isDaemon() is used to check whether a thread is a daemon thread.

Note: isDaemon() is a thread class method.

Daemon Thread:

Question

What is Daemon Thread?

Show Answer

Syntax


final boolean isDaemon()

Parameter

This method does not take any argument value.

Return value

  • booleanValue: It returns True, if the thread is daemon. Otherwise, it returns False.
Thread-2 is set to Daemon Thread

Code

The code snippet below elaborates the use of isDaemon() method in a program:

Edpresso.java
SampleThread.java
// sample class implementing Runnable interface.
public class SampleThread implements Runnable {
// run method for program execution
public void run() {
if(Thread.currentThread().isDaemon())
System.out.println(Thread.currentThread()
.getName() + " is a daemon thread");
else
System.out.println(Thread.currentThread()
.getName() +" is a user thread");
}
}

Explanation

Edpresso.java

  • Line 6: We create SampleThread instance sample because it implements a Runnable interface.
  • Line 7: We create a Thread instance thread1 with sample and thread “Thread 1”.
  • Line 8: We create a second Thread instance thread2 with sample and thread “Thread 2” to the constructor.
  • Line 10: We mark Thread 1 as daemon thread i.e. thread1.setDaemon(true).
  • Line 11: thread2.Start() begins execution of thread2 by calling JVM to call run() method from Runnable interface.
  • Line 12: thread1.Start() begins execution of thread1 by calling JVM to call run() method from Runnable interface.

SampleThread.java

  • Line 5: We check if the current thread is marked as daemon thread or not.
  • Line 6: If the current thread is daemon, it shows a proper message. i.e.,"Thread 1 is a daemon thread".
  • Line 9: If the current thread is not daemon, it shows a proper message. i.e.,"Thread 2 is a user thread".

RELATED TAGS

java programming
Did you find this helpful?