Java
allows us to create two types of threads –
§ Non-Daemon
threads.
§ Daemon
Threads
A
thread that executes main logic of the project is called non-daemon thread. A thread that is running in background to
provide services to non-daemon threads is called daemon thread. Hence, we can
say daemon threads are service threads. We can’t change the nature of the main
thread to Daemon because it is started by JVM. Hence, it is impossible. Main
thread is always Non-Daemon and it isn’t possible to change the nature of main
thread to Daemon, as it is already started by the JVM before starting our
program.
By
default main thread is non-daemon and for all the remaining threads daemon
nature will be inherited from parent to child thread. Whenever the last
non-daemon thread terminates, automatically all the daemon threads will be
terminated. Garbage collector is a daemon thread. Since garbage collector
provides service destroying of unreferenced objects. It is a low priority
thread so we cannot guarantee its execution and it is also terminated if all
non-daemon threads execution is completed.
Daemon Thread creation –
To
create user defined thread as daemon thread, thread class has the following
method –
§ public final void setDaemon(Boolean on) – if on
value is true – thread is created as daemon, else it is created as non-daemon
thread. Hence, the daemon thread property default value is false. To check
thread is daemon or non-daemon, thread class provides a method public final Boolean isDaemon() returns
true if thread is daemon, else returns false.
Note – setDaemon() method
cannot be called after start() method call, it leads to RE:java.lang.IllegalThreadStateException, because once thread is
created as non-daemon thread then it cannot be converted as daemon.
Example –
public class
Daemon extends Thread{
public void
run()
{
for(int i=0;i<5;i++)
{
System.out.println("LAzy thread");
try{
Thread.sleep(100);
}
catch(InterruptedException
e){
System.out.println("Interrupted exception");
}
}
}
public static void
main(String[] args) {
Daemon d = new
Daemon();
d.setDaemon(true);
//statement-1
d.start();
for(int i=0;i<5;i++)
{
System.out.println("main thread "+i);
}
}
}
Note – If we comment
statement-1, then both main and child threads are non-daemon threads. Hence,
both the threads will be executed, until their execution is completed. If we
aren’t commenting statement-1, then main thread is non-daemon and child thread
is daemon thread. Whenever main thread terminates, automatically child thread
will also be terminated.
No comments:
Post a Comment