What is Thread.isDaemon() function in Java?
Overview
isDaemon() is used to check whether a thread is a daemon thread.
Note:
isDaemon()is a thread class method.
Question
What is Daemon Thread?
Show Answer
Syntax
final boolean isDaemon()
Parameter
This method does not take any argument value.
Return value
booleanValue: It returnsTrue, if the thread is daemon. Otherwise, it returnsFalse.
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 executionpublic void run() {if(Thread.currentThread().isDaemon())System.out.println(Thread.currentThread().getName() + " is a daemon thread");elseSystem.out.println(Thread.currentThread().getName() +" is a user thread");}}
Explanation
Edpresso.java
- Line 6: We create
SampleThreadinstancesamplebecause it implements a Runnable interface. - Line 7: We create a Thread instance
thread1withsampleand thread “Thread 1”. - Line 8: We create a second Thread instance
thread2withsampleand thread “Thread 2” to the constructor. - Line 10: We mark
Thread 1as daemon thread i.e.thread1.setDaemon(true). - Line 11:
thread2.Start()begins execution ofthread2by calling JVM to callrun()method from Runnable interface. - Line 12:
thread1.Start()begins execution ofthread1by calling JVM to callrun()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".