The Java Thread setDaemon() method marks this thread as either a daemon thread or a user thread. The Java Virtual Machine exits when the only threads running are all daemon threads.This method must be called before the thread is started.
DeclarationFollowing is the declaration for java.lang.Thread.setDaemon() method
public final void setDaemon(boolean on)Parameters
on − if true, marks this thread as a daemon thread.
Return ValueThis method does not return any value.
ExceptionIllegalThreadStateException − if this thread is active.
SecurityException − if the current thread cannot modify this thread.
The following example shows the usage of Java Thread setDaemon() method. In this program, we've created a thread class AdminThread by extending Thread class. In constructor, we've set the thread status being Daemon as false using setDaemon() method. In run() method, we're printing the status of the thread being Daemon or not. In main() method, a thread of AdminThread is created and Daemon is set false using setDaemon() method and start() method is called to run the thread.
package com.tutorialspoint; class AdminThread extends Thread { AdminThread() { setDaemon(false); } public void run() { boolean d = isDaemon(); System.out.println("daemon = " + d); } } public class ThreadDemo { public static void main(String[] args) throws Exception { Thread thread = new AdminThread(); System.out.println("thread = " + thread.currentThread()); thread.setDaemon(false); // this will call run() method thread.start(); } }Output
Let us compile and run the above program, this will produce the following result −
thread = Thread[main,5,main] daemon = falseExample: Setting a Daemon Thread as True
The following example shows the usage of Java Thread setDaemon() method. In this program, we've created a thread class AdminThread by extending Thread class. In constructor, we've set the thread status being Daemon as false using setDaemon() method. In run() method, we're printing the status of the thread being Daemon or not. In main() method, a thread of AdminThread is created and Daemon is set True using setDaemon() method and start() method is called to run the thread.
package com.tutorialspoint; class AdminThread extends Thread { AdminThread() { setDaemon(false); } public void run() { boolean d = isDaemon(); System.out.println("daemon = " + d); } } public class ThreadDemo { public static void main(String[] args) throws Exception { Thread thread = new AdminThread(); System.out.println("thread = " + thread.currentThread()); thread.setDaemon(true); // this will call run() method thread.start(); } }Output
Let us compile and run the above program, this will produce the following result −
thread = Thread[main,5,main]
java_lang_thread.htm
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4