InterruptRead.java
3.11 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
package com.github.ltsopensource.tasktracker.interrupter;
import sun.nio.ch.Interruptible;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
abstract class InterruptSupport {
private volatile boolean interrupted = false;
private Interruptible interruptor = new InterruptRead.InterruptibleAdapter() {
public void interrupt() {
interrupted = true;
InterruptSupport.this.interrupt(); // 位置3
}
};
public final boolean execute() throws InterruptedException {
try {
blockedOn(interruptor); // 位置1
System.out.println("=======1");
if (Thread.currentThread().isInterrupted()) { // 立马被interrupted
((InterruptRead.InterruptibleAdapter)interruptor).interrupt();
System.out.println("=======2");
}
// 执行业务代码
bussiness();
System.out.println("=======3");
} finally {
blockedOn(null); // 位置2
System.out.println("=======4");
}
return interrupted;
}
public abstract void bussiness();
public abstract void interrupt();
// -- sun.misc.SharedSecrets --
static void blockedOn(Interruptible intr) { // package-private
sun.misc.SharedSecrets.getJavaLangAccess().blockedOn(Thread.currentThread(), intr);
}
}
public class InterruptRead extends InterruptSupport {
private FileInputStream in;
@Override
public void bussiness() {
File file = new File("/dev/urandom"); // 读取linux黑洞,永远读不完
try {
in = new FileInputStream(file);
byte[] bytes = new byte[1024];
while (in.read(bytes, 0, 1024) > 0) {
//
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public FileInputStream getIn() {
return in;
}
@Override
public void interrupt() {
try {
in.getChannel().close();
System.out.println("=======6");
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String args[]) throws Exception {
final InterruptRead test = new InterruptRead();
Thread t = new Thread() {
@Override
public void run() {
long start = System.currentTimeMillis();
try {
System.out.println("InterruptRead start!");
test.execute();
} catch (InterruptedException e) {
System.out.println("InterruptRead end! cost time : " + (System.currentTimeMillis() - start));
e.printStackTrace();
}
}
};
t.start();
// 先让Read执行3秒
Thread.sleep(30000);
// 发出interrupt中断
// t.interrupt();
}
public static abstract class InterruptibleAdapter implements Interruptible{
public void interrupt(Thread thread) {
interrupt();
}
public abstract void interrupt();
}
}