-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathDaemonExample.java
More file actions
55 lines (48 loc) · 1.24 KB
/
DaemonExample.java
File metadata and controls
55 lines (48 loc) · 1.24 KB
1
2
3
4
5
6
7
8
9
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
// based on: https://crunchify.com/what-is-daemon-thread-in-java-example-attached/
public class DaemonExample extends Thread {
private static final boolean bound = Boolean.parseBoolean(System.getenv("BOUND"));
// false Worker thread continues to run.
// true Worker thread terminates with the main thread
private static final boolean debug = Boolean.parseBoolean(System.getenv("DEBUG"));
public static void main(String[] args) {
int delay;
try {
delay = Integer.parseInt(System.getenv("DELAY"));
} catch (NumberFormatException e) {
delay = 3000;
}
if (debug) {
System.err.println("Main thread starts");
}
DaemonExample t = new DaemonExample();
t.setDaemon(bound);
t.start();
try {
Thread.sleep(delay);
} catch (InterruptedException x) {
}
if (debug) {
System.err.println("Main thread exit");
}
}
public void run() {
Boolean continueRun = true;
try {
while (continueRun) {
continueRun = work();
}
} finally {
System.out.println("background thread exits");
}
}
private Boolean work() {
try {
Thread.sleep(1000);
} catch (InterruptedException x) {
}
if (debug) {
System.err.println("background thread # " + Thread.currentThread().getId() + " works");
}
return true;
}
}