实现说明
中断会关闭阻塞中的通道以类 InterruptibleRead为骨架。
使用要点
- 演示输出是带标签的(
read returned: unexpected、interrupt closed the channel、client still open:),每个操作都会留下自己的一行标注。
常见问题
运行「中断会关闭阻塞中的通道」会打印什么?
整个文件跑完,输出行以 read returned: unexpected、interrupt closed the channel、client still open: 这类前缀开头。
核心语句
Thread reader = new Thread(() -> {
try {
client.read(ByteBuffer.allocate(64));
System.out.println("read returned: unexpected");
} catch (ClosedByInterruptException closed) {
System.out.println("interrupt closed the channel");
}
});
Thread.sleep(100);
代码示例
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ClosedByInterruptException;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
public class InterruptibleRead {
public static void main(String[] args) throws Exception {
ServerSocketChannel server = ServerSocketChannel.open();
server.bind(new InetSocketAddress("127.0.0.1", 0)); // port 0: ephemeral
SocketChannel client = SocketChannel.open(server.getLocalAddress());
SocketChannel accepted = server.accept(); // peer stays silent, read blocks
Thread reader = new Thread(() -> {
try {
client.read(ByteBuffer.allocate(64));
System.out.println("read returned: unexpected");
} catch (ClosedByInterruptException closed) {
System.out.println("interrupt closed the channel");
}
});
reader.start();
Thread.sleep(100);
reader.interrupt(); // a blocking read on an interruptible channel wakes up
reader.join(1000);
System.out.println("client still open: " + client.isOpen());
client.close();
accepted.close();
server.close();
}
}