Java Reference
In-Depth Information
Tip
the JVM starts a garbage collector thread to collect all unused object's memory as a daemon thread.
When a thread is created, its daemon property is the same as the thread that creates it. In other words, a new
thread inherits the daemon property of its creator thread.
Listing 6-17 creates a thread and sets the thread as a daemon thread. The thread prints an integer and sleeps for
some time in an infinite loop. At the end of the main() method, the program prints a message to the standard output
stating that it is exiting the main() method. Since thread t is a daemon thread, the JVM will terminate the application
when the main() method is finished executing. You can see this in the output. The application prints only one integer
from the thread before it exits. You may get a different output when you run this program.
Listing 6-17. A Daemon Thread Example
// DaemonThread.java
package com.jdojo.threads;
public class DaemonThread {
public static void main(String[] args) {
Thread t = new Thread(DaemonThread::print);
t.setDaemon(true);
t.start();
System.out.println("Exiting main method");
}
public static void print() {
int counter = 1 ;
while(true) {
try {
System.out.println("Counter:" + counter++);
Thread.sleep(2000); // sleep for 2 seconds
}
catch(InterruptedException e) {
e.printStackTrace();
}
}
}
}
Exiting main method
Counter:1
Listing 6-18 is the same program as Listing 6-17, except that it sets the thread as a non-daemon thread. Since
this program has a non-daemon (or a user) thread, the JVM will keep running the application, even after the main()
method finishes. You will have to stop this application forcibly because the thread runs in an infinite loop.
 
Search WWH ::




Custom Search