|There are two types of threads user thread and daemon thread. The daemon thread is a service provider thread. It provides services to the user thread. Its life depends on the user threads i.e. when all the user threads dies, JVM terminates this thread automatically.|
Points to remember for Daemon Thread:
- It provides services to user threads for background supporting tasks. It has no role in life than to serve user threads.
- Its life depends on user threads.
- It is a low priority thread.
Why JVM terminates the daemon thread if there is no user thread remaining?
|The sole purpose of the daemon thread is that it provides services to user thread for background supporting task. If there is no user thread, why should JVM keep running this thread. That is why JVM terminates the daemon thread if there is no user thread.|
Methods for Daemon thread:
|The java.lang.Thread class provides two methods related to daemon thread
- public void setDaemon(boolean status): is used to mark the current thread as daemon thread or user thread.
- public boolean isDaemon(): is used to check that current is daemon.
Simple example of Daemon thread
Note: If you want to make a user thread as Daemon, it must not be started otherwise it will throw IllegalThreadStateException.
Output:exception in thread main: java.lang.IllegalThreadStateException