Tutorspoint provides Daemon Threads JAVA Homework Help and programming help for computer science students
Consider the following example:
JVM executes a .class file and while in this process, many objects will be created. Simultaneously, garbage collector collects all the UN -referred objects in the background. Thus, garbage collector is background process. In other words, garbage collector thread provides its services in the background to support the JVM thread, and as long as JVM thread is in execution, the garbage collector thread will also be in execution. In this case, garbage collector thread is nothing but a Daemon thread.
Concept of Daemon threads:
Concept of Daemon threads is to design a thread with infinite loop which would be supporting the parent thread as a background process and it is suppose to get executed along with parent thread. Also, this background thread should stop, when the parent thread stops.
- We can define daemon threads by using set Daemon () method.
- If we want to set a thread as Daemon thread , then pass Boolean value ‘true’ to the method, as shown below.
Obj. Set Daemon (true);
Daemon threads would never be joined. Not even in main (which is the default join). Once the control comes out of the parent thread, the daemon thread is automatically terminated.
Class Daemon demo extends Thread
Public void main ()
System. Out. Prinln(“Daemon : “ +i);
Public static void main (string args [ ])
Daemon demo d = new Daemon demo ();
d. set Daemon ( true);
d. start ();
For (int i=100; I < 137; i++)
System. Out. Prinln(“main : “ +i);
System. Out. Prinln(“ end of main “ );