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 itsstart()API method. - The class overrides the
run()method of Runnable, where it sleeps forever. We create a new instance ofMyDaemonThreadclass in amain()method. The method checks if the thread is a daemon, usingisDaemon()method ofMyDaemonThreadand 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.
