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.
final void setDaemon(boolean on)
The Thread.setdaemon()
method takes a single boolean type argument.
on
: If this value is set to true
, then the current thread is marked as a daemon thread.A void
The following exceptions can occur from the setdaemon()
method:
IllegalThreadStateException
: If a thread was started and has not been completed yet, then the setdaemon()
method will throw this exception.SecurityException
: If the current thread does not have access to modify the thread, then the setdaemon()
method will throw this exception.Note: We can also learn to check whether a thread is a daemon thread or not from this shot.
// 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();}}
isDaemon()
method to check if the thread is a daemon thread.Main.class
and extending the Thread
class.thread1
and thread2
user threads as daemon threads by calling the setDaemon(true)
method.start()
method to start the threads that we created earlier. Then, we call the run()
(see line 5) method to check whether this thread is a daemon thread.