forked from douglascraigschmidt/LiveLessons
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGCDRunnable.java
More file actions
87 lines (79 loc) · 2.73 KB
/
GCDRunnable.java
File metadata and controls
87 lines (79 loc) · 2.73 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
import java.util.Random;
/**
* @class GCDRunnable
*
* @brief Computes the greatest common divisor (GCD) of two numbers.
* This implementation is identical to the one in
* UserOrDaemonRunnable.
*/
public class GCDRunnable
extends Random // Inherits random number generation capabilities.
implements Runnable {
/**
* 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 GCDRunnable(String threadType) {
this.threadType = threadType;
}
/**
* 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, sleeping for half a
* second at a time.
*/
public void run() {
final String threadString =
" with "
+ threadType
+ " thread id "
+ Thread.currentThread();
System.out.println("Entering run()"
+ threadString);
try {
// Iterate for the give number of times.
for (int i = 0; i < MAX_ITERATIONS; ++i) {
// Generate two random numbers (nextInt() obtained
// from Random superclass).
int number1 = nextInt();
int number2 = 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);
}
}
}