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:

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.

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