Skip to content

Instantly share code, notes, and snippets.

@jingz8804
Created October 21, 2014 00:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jingz8804/d42ce715e4f86a5cb727 to your computer and use it in GitHub Desktop.
Save jingz8804/d42ce715e4f86a5cb727 to your computer and use it in GitHub Desktop.
Java Daemon Example, all credit to user Sreekesh Okky in this post http://stackoverflow.com/questions/2213340/what-is-daemon-thread-in-java
public class App{
public static void main(String[] args){
DaemonThread dt = new DaemonThread();
dt.setDaemon(true); // must be set before thread starting;
dt.start(); // spawning the thread
try{
Thread.sleep(3000); // wait for 3 seconds. This actually let the daemon thread to print out some messages.
}catch(InterruptedException e){
}
System.out.println("Leaving main method");
}
}
public DaemonThread extends Thread{
public void run(){
System.out.println("Entering the run method");
try {
System.out.println("In run Method: currentThread() is" + Thread.currentThread());
while (true) { // a daemon thread usually involves a infinite loop in the run method
try {
Thread.sleep(500);
} catch (InterruptedException x) {}
// as long as the non-daemon thread is running (in this case, the main thread)
// this thread prints out the following message every 0.5 second.
System.out.println("In run method: woke up again");
}
} finally {
// the message in the finally block won't be printed out
// since when the JVM halts, finally block in daemon thread is not executed.
System.out.println("Leaving run Method");
}
}
}
Entering main Method
Entering run method
In run Method: currentThread() isThread[Thread-0,5,main]
In run method: woke up again
In run method: woke up again
In run method: woke up again
In run method: woke up again
In run method: woke up again
In run method: woke up again
Leaving main method
===============================
As we can see here, while the main thread in sleep, the daemon thread performed 6 printing service.
When the main thread wakes up, it prints out the leaving message and exits.
At this point, there are no more non-daemon threads in the program, so the JVM halts.
That message in the finally block of the daemon thread never got printed.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment