Java Programming Tutorials

Java programming tutorials with many code examples!

Java daemon thread


How to create Java daemon thread? How to create it? What are its properties? In the following example we’ll show Java daemon threads in action.


In the below code we’ll create and start 5 daemon threads. Each of them will sleep for 3 seconds to mark that they are really running. The main thread will finish just after creating all the threads:


import java.util.concurrent.TimeUnit;

public class ThreadDaemon {

    private static class SampleThread extends Thread {
        private final int id;

        public SampleThread(int id) {
   = id;

        public void run() {
            System.out.println("Running thread " + id);
            try {
            } catch (InterruptedException e) {
            } finally {
                System.out.println("Finally in thread " + id);
            System.out.println("Stopping thread " + id);

    public static void main(String[] args) {
        System.out.println("Starting threads:");
        for (int i = 1; i <= 5; ++i) {
            Thread t = new SampleThread(i);
            // Daemon trigger:
        System.out.println("Stopping program");

Note that we use TimeUnit class to call sleep() method instead of Thread.sleep(). Since Java 5 this is the preferred way, because its simple more readable.

When we run the above program we can see that the program ends without giving the daemon threads a chance to end properly and execute their finally blocks:

Starting threads:
Running thread 1
Running thread 2
Running thread 3
Running thread 4
Stopping program

Here’s the same program, but with one, small change – commented out setDaemon(true) line:

Starting threads:
Running thread 1
Running thread 2
Running thread 3
Running thread 4
Stopping program
Running thread 5
Finally in thread 1
Stopping thread 1
Finally in thread 2
Stopping thread 2
Finally in thread 3
Stopping thread 3
Finally in thread 4
Stopping thread 4
Finally in thread 5
Stopping thread 5

As you can see, when the threads are not daemons, the program is waiting for them to finish and calls finally block.

Another important thing is that threads created from daemon threads are also daemon threads!

Share with the World!