-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPiInterrupt.java
More file actions
52 lines (43 loc) · 1.06 KB
/
Copy pathPiInterrupt.java
File metadata and controls
52 lines (43 loc) · 1.06 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
package threadbook.ch05;
public class PiInterrupt extends Object implements Runnable {
private double latestPiEstimate;
public void run() {
try {
System.out.println("for comparison, Math.PI=" +
Math.PI);
calcPi(0.000000001);
System.out.println("within accuracy, latest pi=" +
latestPiEstimate);
} catch ( InterruptedException x ) {
System.out.println("INTERRUPTED!! latest pi=" +
latestPiEstimate);
}
}
private void calcPi(double accuracy)
throws InterruptedException {
latestPiEstimate = 0.0;
long iteration = 0;
int sign = -1;
while ( Math.abs(latestPiEstimate - Math.PI) >
accuracy ) {
if ( Thread.interrupted() ) {
throw new InterruptedException();
}
iteration++;
sign = -sign;
latestPiEstimate +=
sign * 4.0 / ( ( 2 * iteration ) - 1 );
}
}
public static void main(String[] args) {
PiInterrupt pi = new PiInterrupt();
Thread t = new Thread(pi);
t.start();
try {
Thread.sleep(10000);
t.interrupt();
} catch ( InterruptedException x ) {
// ignore
}
}
}