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
74 lines (68 loc) · 2.46 KB
/
GCDRunnable.java
File metadata and controls
74 lines (68 loc) · 2.46 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
import java.util.Random;
/**
* @class GCDRunnable
*
* @brief Computes the greatest common divisor (GCD) of two numbers.
*/
public class GCDRunnable
extends Random // Inherits random number generation capabilities.
implements Runnable {
/**
* Number of times to iterate, which is 100 million to ensure the
* program runs for a while.
*/
private final int MAX_ITERATIONS = 100000000;
/**
* 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 thread id "
+ Thread.currentThread();
System.out.println("Entering run()"
+ threadString);
try {
for(int i = 0; i < MAX_ITERATIONS; ++i) {
// Generate two random numbers.
int number1 = nextInt();
int number2 = nextInt();
// Check to see if the thread's been interrupted.
if(Thread.interrupted())
throw new InterruptedException();
// Print results every 10 million iterations.
else if((i % 10000000) == 0)
System.out.println("In run()"
+ threadString
+ " the GCD of "
+ number1
+ " and "
+ number2
+ " is "
+ computeGCD(number1,
number2));
}
} catch (InterruptedException e) {
System.out.println("Thread interrupted"
+ threadString);
} finally {
System.out.println("Leaving run() "
+ threadString);
}
}
}