Java Thread setDaemon() method
The setDaemon() method of thread class is used to mark the thread either daemon thread or a user thread. Its life depends on the user threads i.e. when all user threads die, JVM terminates this thread automatically. It must be invoked before the thread is started.
If you call the setDaemon() method after stating of the thread, this method will throw IllegalThreadStateException.
on: If true, marks the thread as a daemon thread.
This method will return true if the thread is daemon thread otherwise return false.
IllegalThreadStateException: If the thread is alive.
SecurityException: If the current thread cannot modify the thread.
Example 1Test it Now
daemon thread work daemon thread work user thread work
When you call the setDaemon() method after starting of thread.Test it Now
Name of thread: Thread-0 Daemon: false Exception in thread "main" java.lang.IllegalThreadStateException at java.lang.Thread.setDaemon(Thread.java:1359) at JavaSetDaemonExp2.main(JavaSetDaemonExp2.java:17)