Saturday, April 8, 2017

Java Daemon Thread with Example

The Threads which are executing in the background are called Daemon Threads. A thread has to continuously execute without any interruption to provide services to other threads or objects.It generally provides a background processing. The main objective of Daemon Thread is to provide support for non-Daemon threads. For Example: Garbage Collector.

We can check whether the Thread is Damon or not by using public final boolean isDaemon() method. We can change Daemon() nature of a thread by using setDaemon() method.
public final void setDaemon(boolean b)

We must remember,we can change Daemon() nature before starting thread only. If after starting a thread if we are trying to change demonstration then we will get Run time Exception says illegalThreadstateException.

main() thread is always non-daemon() and we can not change it's Daemon() nature because it is already started at the beginning only.If the parent class is Daemon() then child class is also Daemon() and if the parent is non-Daemon() , child is also non-daemon()

Note: whenever last non-daemon() thread terminates automatically all Daemon() threads will be terminated.

Example:
class myThread extends Thread
{
public void run()
{
for(int i=0;i<10;i++)
{
System.out.println("Lazy Thread");
try{
Thread.sleep(2000);
}
catch(InterruptedException ie)
{
}
}
}
}
class DaemonThreadDemo
{
public static void main(String args[])
{
myThread t=new myThread();
t.setDaemon(true);         
t.start();
System.out.println("end of main method");
}
}
Output:
End of main method
Lazy Thread

If we are comment t.setDaemon(true) then both main() and child() threads are non-Daemon() and hence both will be executed until their completion. If we are not comment t.setDaemon(true) then main() method is non-Daemon() and child thread is Daemon() and hence whenever main() thread terminates automatically child thread will be terminated.

ALSO READ TOP POSTS:
Difference between web server and application server
Common interview Questions and answers
Java Exception interview Questions 
What are the First things you do after joining the company
inter thread communication in java with examples
When to use abstract class and interface in Java

No comments:

Post a Comment

High Paying Jobs after Learning Python

Everyone knows Python is one of the most demand Programming Language. It is a computer programming language to build web applications and sc...