forked from hansiming/JavaProject
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInterruptingIdiom.java
More file actions
89 lines (59 loc) · 1.55 KB
/
InterruptingIdiom.java
File metadata and controls
89 lines (59 loc) · 1.55 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
package com.csdhsm.concurrent;
import java.util.concurrent.TimeUnit;
class NeedsCleanup {
private final int id;
public NeedsCleanup(int ident) {
id = ident;
System.out.println("NeedsCleanup" + id);
}
public void cleanup() {
System.out.println("Cleaning up" + id);
}
}
class Blocked3 implements Runnable {
private volatile double d = 0.0;
@Override
public void run() {
try {
while (!Thread.interrupted()) {
// point1
NeedsCleanup n1 = new NeedsCleanup(1);
// Start try-finally immediately after definition
// of n1,to guarantee proper cleanup of n1
try {
System.out.println("Sleep");
TimeUnit.SECONDS.sleep(1);
// Poing2
NeedsCleanup n2 = new NeedsCleanup(2);
try {
System.out.println("Calculating");
// A time-consuming, non-blocking operation
for (int i = 1; i < 2500000; i++) {
d = d + (Math.PI + Math.E) / d;
}
System.out.println("Finished time-consuming operation");
} finally {
n2.cleanup();
}
} finally {
n1.cleanup();
}
}
System.out.println("Exiting via while() test");
} catch (InterruptedException e) {
System.out.println("Exiting via InterruptedException");
}
}
}
public class InterruptingIdiom {
public static void main(String[] args) throws Exception {
/*if(args.length != 1){
System.out.println("usage: java InterruptingIdop, delay-in-mS");
System.exit(1);
}*/
Thread t = new Thread(new Blocked3());
t.start();
TimeUnit.MILLISECONDS.sleep(5000);
t.interrupt();
}
}