Skip to content

Commit c8d48f6

Browse files
committed
ok
1 parent 307b10b commit c8d48f6

14 files changed

Lines changed: 130 additions & 72 deletions

File tree

.idea/workspace.xml

Lines changed: 67 additions & 72 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.
695 Bytes
Binary file not shown.
1.39 KB
Binary file not shown.
897 Bytes
Binary file not shown.
978 Bytes
Binary file not shown.
Binary file not shown.
792 Bytes
Binary file not shown.
1.23 KB
Binary file not shown.
983 Bytes
Binary file not shown.
Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
package com.xforg.concurrency;//: concurrency/InterruptingIdiom.java
2+
// General idiom for interrupting a task.
3+
// {Args: 1100}
4+
import java.util.concurrent.*;
5+
6+
class NeedsCleanup {
7+
private final int id;
8+
public NeedsCleanup(int ident) {
9+
id = ident;
10+
System.out.println("NeedsCleanup " + id);
11+
}
12+
public void cleanup() {
13+
System.out.println("Cleaning up " + id);
14+
}
15+
}
16+
17+
class Blocked3 implements Runnable {
18+
private volatile double d = 0.0;
19+
public void run() {
20+
try {
21+
while(!Thread.interrupted()) {
22+
// point1
23+
NeedsCleanup n1 = new NeedsCleanup(1);
24+
// Start try-finally immediately after definition
25+
// of n1, to guarantee proper cleanup of n1:
26+
try {
27+
System.out.println("Sleeping");
28+
TimeUnit.SECONDS.sleep(1);
29+
// point2
30+
NeedsCleanup n2 = new NeedsCleanup(2);
31+
// Guarantee proper cleanup of n2:
32+
try {
33+
System.out.println("Calculating");
34+
// A time-consuming, non-blocking operation:
35+
for(int i = 1; i < 2500000; i++)
36+
d = d + (Math.PI + Math.E) / d;
37+
System.out.println("Finished time-consuming operation");
38+
} finally {
39+
n2.cleanup();
40+
}
41+
} finally {
42+
n1.cleanup();
43+
}
44+
}
45+
System.out.println("Exiting via while() test");
46+
} catch(InterruptedException e) {
47+
System.out.println("Exiting via InterruptedException");
48+
}
49+
}
50+
}
51+
52+
public class InterruptingIdiom {
53+
public static void main(String[] args) throws Exception {
54+
if(args.length != 1) {
55+
System.out.println("usage: java InterruptingIdiom delay-in-mS");
56+
System.exit(1);
57+
}
58+
Thread t = new Thread(new Blocked3());
59+
t.start();
60+
TimeUnit.MILLISECONDS.sleep(new Integer(args[0]));
61+
t.interrupt();
62+
}
63+
}

0 commit comments

Comments
 (0)