Daemon Thread:
1. The thread which are executing in background is called Daemon thread .
For example:-Garbage Collector,Signal Dispatcher,Attach Listener etc.
2.The main objective of daemon Thread is to provide support to Non-daemon thread .
3. Usually daemon thread having low priority but based on our requirement daemon thread can also run with high priority by JVM .
4. By default main thread is always non-daemon and for all remaining thread daemon nature is inherited i.e if the parent thread is daemon then automatically child thread is also daemon and vice -versa.
5.JVM terminate all daemon thread when all user thread finish their execution.
Note:-Changing nature of thread to daemon is only possible before starting a thread .After starting a thread if we are trying to change thread to daemon thread then it will throw an exception illegalThreadStateException on runtime.
it is impossible to convert main thread to daemon thread because it is already started by JVM at the beginning.
Methods:
1.public boolean isDaemon();
2.public void setDaemon();
Programs:-
class daemonThread extends Thread{
public void run(){}
public static void main(String args[])
{
System.out.println("Is main thread is daemon thread -->"+Thread.currentThread().isDaemon());
daemonThread d1=new daemonThread();
System.out.println("Is d1 thread is daemon thread -->"+d1.isDaemon());
d1.setDaemon(true);//setting thread to daemon thread
System.out.println("Is d1 thread is daemon thread -->"+d1.isDaemon());
}
}
After starting a thread if we are trying to change thread to daemon thread then it will throw an exception illegalThreadStateException on runtime.
class daemonThread extends Thread{
public void run(){}
public static void main(String args[])
{
daemonThread d1=new daemonThread();
d1.start();
d1.setDaemon(true);
}
}
it is impossible to convert main thread to daemon thread because it is already started by JVM at the beginning.
class daemonThread extends Thread{
public void run(){}
public static void main(String args[])
{
Thread.currentThread().setDaemon(true);
}
}
Application:
Daemon thread is to provide services to user thread for background supporting task.
Comments
Post a Comment