-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNIOInterruption.java
More file actions
69 lines (57 loc) · 1.7 KB
/
NIOInterruption.java
File metadata and controls
69 lines (57 loc) · 1.7 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
package Thread.interrupt;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
/*
* 普通的Io阻塞,不可中断(就是还停留在阻塞状态,不能跳出阻塞状态)
* 还有锁,,也是不可中断的
*
* sleep阻塞是可中断的,可以跳出阻塞状态
*
*
* nio自动响应中断
*
* */
class NIOBlocked implements Runnable{
private final SocketChannel channel;
public NIOBlocked(SocketChannel socketChannel){
this.channel=socketChannel;
}
public void run() {
try {
System.out.println("waiting for read() in:"+this);
channel.read(ByteBuffer.allocate(1));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("exiting NIOBlocked.run()");
}
}
public class NIOInterruption {
public static void main(String[] args) {
ExecutorService es=Executors.newCachedThreadPool();
try {
ServerSocket serverSocket=new ServerSocket(8080);
InetSocketAddress isa=new InetSocketAddress("localhost", 8080);
SocketChannel channel1=SocketChannel.open(isa);
SocketChannel channel2=SocketChannel.open(isa);
//将中断发送给一个特定的线程
Future<?> future=es.submit(new NIOBlocked(channel1));
es.execute(new NIOBlocked(channel2));
//中断任务
es.shutdown();
future.cancel(true);
//关闭底层资源来释放锁
channel2.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}