Daemon Thread
Daemon thread in Java is a service provider thread that provides services to the user thread.
Its life depends on the mercy of the user threads i.e when the entire threads die, JVM
terminates this (means Daemon thread) thread automatically.
There are many Java daemon threads running automatically i.e Garbage collector, finalizer
etc
JVM
Other Daemon thread
Main Thread
Eg. Gargbage collector
Start() start()
Thread A Thread B
Method:
1] public final void setDaemon(boolean) :- marks the thread as daemon
2] public final boolean isDaemon() : - tests if the thread is a daemon thread.
class Test extends Thread
{
public void run()
{
[Link](“Child Thread”); //Daemon thread
}
public static void main(String args[])
{
[Link](“Main Thread”);
Test t=new Test();
[Link](true); //create Daemon thread
[Link]();
}
Note:
Case 1:
i. We have to create Daemon thread before starting the thread.
ii. If we create Daemon thread after the starting the thread, it will create runtime
exception i.e IllegalThreadStateException.
Case 2:
We cannot create main thread as Daemon Thread.
i.e. [Link](true);
class Test extends Thread
{
public void run()
{
[Link](“Child Thread”); //Daemon thread
}
Public static void main(String args[])
{
[Link](true);
[Link](“Main Thread”);
Test t=new Test();
[Link](true); //create Daemon thread
[Link]();
}
class Test extends Thread
{
public void run()
{
If([Link]().isDaemon())
[Link](“DaemonThread”); //Daemon thread
else
[Link](“User Thread”);
}
Public static void main(String args[])
{
[Link](“Main Thread”);
Test t1=new Test();
Test t2=new Test();
Test t3=new Test();
[Link](true); //create Daemon thread
[Link]();
[Link]();
[Link]();
}