forked from hansiming/JavaProject
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInterrupting.java
More file actions
110 lines (79 loc) · 2.1 KB
/
Interrupting.java
File metadata and controls
110 lines (79 loc) · 2.1 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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
package com.csdhsm.concurrent;
import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
class SleepBlocked implements Runnable{
@Override
public void run() {
try {
TimeUnit.SECONDS.sleep(100);
} catch (InterruptedException e) {
System.out.println("InterruptedException With SleepBlocked");
}
System.out.println("Exiting SleepBlocked.run()");
}
}
class IOBlocked implements Runnable{
private InputStream in;
public IOBlocked(InputStream is) {
in = is;
}
@Override
public void run() {
try {
System.out.println("Waiting for read():");
in.read();
} catch (IOException e) {
if(Thread.currentThread().isInterrupted()){
System.out.println("Interrupted from blocked I/O");
}else{
System.out.println("NOT Interrupted from blocked I/O");
throw new RuntimeException(e);
}
}
System.out.println("Exiting IOBlocked.run()");
}
}
class SynchronziedBlocked implements Runnable{
public synchronized void f(){
while(true){
//Never releases lock
Thread.yield();
}
}
public SynchronziedBlocked() {
new Thread(){
@Override
public void run() {
f();
}
}.start();
}
@Override
public void run() {
System.out.println("Trying to call f()");
f();
System.out.println("Exiting SynchronizedBlocked.run()");
}
}
public class Interrupting {
private static ExecutorService exec = Executors.newCachedThreadPool();
static void test(Runnable r) throws Exception{
Future<?> f = exec.submit(r);
TimeUnit.MILLISECONDS.sleep(100);
System.out.println("Interrupting -->" + r.getClass().getName());
f.cancel(true);
System.out.println("Interrupt sent to -->" + r.getClass().getName());
}
public static void main(String[] args) throws Exception {
test(new SleepBlocked());
test(new IOBlocked(System.in));
test(new SynchronziedBlocked());
TimeUnit.SECONDS.sleep(3);
System.out.println("Aboring with System.exit(0)");
System.exit(0);
}
}