forked from douglascraigschmidt/LiveLessons
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUserOrDaemonThread.java
More file actions
98 lines (89 loc) · 3.23 KB
/
Copy pathUserOrDaemonThread.java
File metadata and controls
98 lines (89 loc) · 3.23 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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
import java.util.Random;
/**
* @class UserOrDaemonThread
*
* @brief This class demonstrates the difference between a Java user
* thread and a daemon thread. If its constructor is passed
* "true" it becomes a "daemon" thread, which exits when the
* main thread exits. If it's passed "false" it's a "user"
* thread, which can continue to run even after the main thread
* exits.
*/
public class UserOrDaemonThread extends Thread {
/**
* Keep track of whether this is a "user" or a "daemon" thread.
*/
final private String threadType;
/**
* Number of times to iterate, which is 100 million to ensure the
* program runs for a while.
*/
private final int MAX_ITERATIONS = 100000000;
/**
* Constructor determines what type of thread it being created.
*/
public UserOrDaemonThread(Boolean daemonThread) {
if (daemonThread) {
// Become a daemon thread (setDaemon() obtained from the
// superclass).
setDaemon(true);
threadType = "daemon";
} else
threadType = "user";
}
/**
* Provides a recursive implementation of Euclid's algorithm to
* compute the "greatest common divisor" (GCD), which is the
* largest positive integer that divides two integers without a
* remainder.
*/
private int computeGCD(int number1,
int number2) {
// Basis case.
if (number2 == 0)
return number1;
// Recursive call.
return computeGCD(number2,
number1 % number2);
}
/**
* Hook method that runs for MAX_ITERATIONs.
*/
public void run() {
final String threadString =
" with "
+ threadType
+ " thread id "
+ Thread.currentThread();
System.out.println("Entering run()"
+ threadString);
// Create a new Random number generator. We need to allocate
// a new Random object dynamically since we can't inherit from
// Random since we already inherit from Thread and Java only
// allows single inheritance.
Random random = new Random();
try {
// Iterate for the given # of iterations.
for (int i = 0; i < MAX_ITERATIONS; ++i) {
// Generate two random numbers.
int number1 = random.nextInt();
int number2 = random.nextInt();
// Print results every 10 million iterations.
if ((i % 10000000) == 0)
System.out.println("In run()"
+ threadString
+ " the GCD of "
+ number1
+ " and "
+ number2
+ " is "
+ computeGCD(number1,
number2));
}
}
finally {
System.out.println("Leaving run() "
+ threadString);
}
}
}