What is the Thread.setdaemon() method in Java?
The Thread.setdaemon() method is used to set a thread either as a daemon thread or as a user-defined thread. It signals
Note: Daemon threads are low priority threads that execute in the background to perform low priority tasks like a user-defined thread service, garbage collection, and so on.
Syntax
final void setDaemon(boolean on)
Parameter values
The Thread.setdaemon() method takes a single boolean type argument.
on: If this value is set totrue, then the current thread is marked as a daemon thread.
Return value
A void
Exceptions
The following exceptions can occur from the setdaemon() method:
IllegalThreadStateException: If a thread was started and has not been completed yet, then thesetdaemon()method will throw this exception.SecurityException: If the current thread does not have access to modify the thread, then thesetdaemon()method will throw this exception.
Note: We can also learn to check whether a thread is a daemon thread or not from this shot.
Code example
// Program to test setDaemon() method// Main classpublic class Main extends Thread {// run method for threadspublic void run() {//check either daemon thread or notif(Thread.currentThread().isDaemon()) {System.out.println("Daemon thread");}else {System.out.println("User defined thread");}}public static void main(String[] args) {// create four threadsMain thread1= new Main();Main thread2= new Main();Main thread3= new Main();Main thread4= new Main();// set thread1 to daemon threadthread1.setDaemon(true);// invoke run() methodthread1.start();// set thread2 to daemon threadthread2.setDaemon(true);// start remaining threadsthread2.start();thread3.start();thread4.start();}}
Code explanation
- Line 7: We invoke the
isDaemon()method to check if the thread is a daemon thread. - Lines 16–19: We create four threads by instantiating the
Main.classand extending theThreadclass. - Lines 21 and 25: We set the
thread1andthread2user threads as daemon threads by calling thesetDaemon(true)method. - Lines 27–29: We invoke the
start()method to start the threads that we created earlier. Then, we call therun()(see line 5) method to check whether this thread is a daemon thread.