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 ofMyDaemonThread
class in amain()
method. The method checks if the thread is a daemon, usingisDaemon()
method ofMyDaemonThread
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:
01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 | 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.