Home » Core Java » threads » Daemon Thread example

About Ilias Tsagklis

Ilias Tsagklis
Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor at Java Code Geeks.

Daemon Thread example

With this example we are going to demonstrate how to create a daemon Thread. We have implemented a class, MyDaemonThread, that implements the Runnable, as described below:

  • The runnable creates a new Thread, marks it as a daemon, using setDaemon(boolean on) API method of Thread, and then begins the thread’s execution calling its start() API method.
  • The class overrides the run() method of Runnable, where it sleeps forever. We create a new instance of MyDaemonThread class in a main() method. The method checks if the thread is a daemon, using isDaemon() method of MyDaemonThread and if so, it sleeps and then exits since the daemon thread is the only one running.

Let’s take a look at the code snippet that follows:

package com.javacodegeeks.snippets.core;

class MyDaemonThread implements Runnable {

    Thread thrd;

    MyDaemonThread() {

  thrd = new Thread(this);

  thrd.setDaemon(true);

  thrd.start();
    }

    public boolean isDaemon() {

  return thrd.isDaemon();
    }

    @Override
    public void run() {

  try {


while (true) {


    System.out.print(".");


    Thread.sleep(100);


}

  } catch (Exception ex) {


System.out.println("MyDaemon interrupted.");

  }
    }
}

public class DeamonThreadExample {

    public static void main(String args[]) throws Exception {

  MyDaemonThread deamonThread = new MyDaemonThread();

  if (deamonThread.isDaemon()) {


System.out.println("Daemon thread.");

  }


  Thread.sleep(10000);

  System.out.println("nMain thread ending.");
    }
}

Output:

Daemon thread.
.....................................................................................................
Main thread ending.

  
This was an example of how to create a daemon Thread in Java.

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

 

Subscribe
Notify of
guest
The comment form collects your name, email and content to allow us keep track of the comments placed on the website. Please read and accept our website Terms and Privacy Policy to post a comment.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments