forked from hansiming/JavaProject
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNIOInterruption.java
More file actions
82 lines (57 loc) · 1.83 KB
/
NIOInterruption.java
File metadata and controls
82 lines (57 loc) · 1.83 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
package com.csdhsm.concurrent;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousCloseException;
import java.nio.channels.ClosedByInterruptException;
import java.nio.channels.SocketChannel;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
/**
* @Title: NIOInterruption.java
* @Package: com.csdhsm.concurrent
* @Description
* @author Han
* @date 2016-4-11 下午6:25:29
* @version V1.0
*/
class NIOBlocked implements Runnable{
private final SocketChannel sc;
public NIOBlocked(SocketChannel sc) {
this.sc = sc;
}
@Override
public void run() {
try {
System.out.println("Waiting for read() in " + this);
sc.read(ByteBuffer.allocate(1));
} catch (ClosedByInterruptException e){
System.out.println("ClosedByInterruptException");
} catch (AsynchronousCloseException e){
System.out.println("AsynchronousCloseException");
} catch (IOException e) {
throw new RuntimeException(e);
}
System.out.println("Exiting NIOBlocked.run() " + this);
}
}
public class NIOInterruption {
@SuppressWarnings("unused")
public static void main(String[] args) throws IOException, Exception {
ExecutorService service = Executors.newCachedThreadPool();
ServerSocket socket = new ServerSocket(8080);
InetSocketAddress isa = new InetSocketAddress("localhost", 8080);
SocketChannel sc1 = SocketChannel.open(isa);
SocketChannel sc2 = SocketChannel.open(isa);
Future<?> f = service.submit(new NIOBlocked(sc1));
service.execute(new NIOBlocked(sc2));
service.shutdown();
TimeUnit.SECONDS.sleep(1);
f.cancel(true);
TimeUnit.SECONDS.sleep(1);
sc2.close();
}
}