Friday, February 13, 2009

Daemon Thread

The threads which are executing in the background to provide support for user defined threads are called daemon threads.
Ex: garbage callector
Thread class contain the following method for checking whether the given thread is daemon or not
Public final Boolean isDaemon();
Daemon thread Example:
Class DaemonThread
{
Public static void main(string []args)
{
s.o.pln(thread .currentThread().isDaemon());
}
}
Usually daemon threads runnigg with low priority but based on our requirement we can
give high priority also,The daemon nature is inherited from the parent..ie of the parent is the daemon thread then the child also daemon thread and the parent n non-daemon by default child also non-daemon.
Based on our requirement we are allowed to change the daemon nature of any thread b the following method.
Public final setDaemon(Boolean b);
if b is true the thread will become daemon otherwise non-Daemon
Example:class sample extends thread
{
{
Public static void main(String[] a)
{
MyThread t=new MyThread();
t.start();
t.setDaemon(true);
System.out.println(t.asDaemon());
we are not allowed to change Daemon nature after starting a thread,validation leads to RTE saying “illegal thread state Exception”
ie we are not allowed to change Daemon nature of main method it is already started at the beginning only.
Whenever the last non-Daemon thread dead all the Daemon threads will be terminated automatically
Class MyThread extends Thread
{
Public void run()
{
For(int i=0;i<10;i++)
{
s.o.pln(“childmethod”);
try
{
Thread.sleep(2000);
}
Catch(InterruptedException e) {}
}
}
}
Class DaemonThreadExample
{
public static void main(string[]args)threads IE
{
MyThread t=new Thread();
System.out.println(t.isDaemon());
t.setDaemon(true);
t.start();
thread.sleep(5000);
System.out.println(“end of main thread”);
}
}
After starting the thread we are allowed to change the priority of a thread but not allowed to change the Daemon nature.

0 comments:

Post a Comment