threads

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.

Ilias Tsagklis

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

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

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button