一、blocking/non-blocking | sync/async
1.blocking/non-blocking: 描述的是方法会不会阻塞线程的执行,使线程进入blocking状态
2.sync/async:描述的是数据读写方式
- sync:用户线程参与数据读写
- 由内核线程发起读写,用户只需要关注I/O完成后的回调,不需要参与具体的I/O过程
二、AIO(Asynchronous Input and Output)
- NIO2.0提出了新异步通道概念,并提供了异步文件通道和异步套接字实现的通道(JDK7)
- 异步套接字通道真正的实现了真正的异步非阻塞I/O
三、三种IO工作原理
四、AIO模型
五、BIO、NIO、AIO
I/O | 数据传输 | 时间 | 实现方式 | 使用场景 | 应用 |
---|---|---|---|---|---|
BIO | Stream | JDK1 | Socket | 连接数目比较小且固定的架构 | 一般很少使用 |
NIO | ByteBuffer | JDK4 | Channel Selector | 连接数目多且连接比较短(轻操作)的架构 | 网络框架netty |
AIO | ByteBuffer | JDK7 | Channel | 连接数目多且连接比较长(重操作)的架构 | Ngix,MySQL新版本 |
六、AIO实现
//TestServer.java
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
public class TestServer {
private AsynchronousServerSocketChannel channel = null;
public TestServer(int port) {
try {
channel = AsynchronousServerSocketChannel.open().bind(new InetSocketAddress(port));
} catch (IOException e) {
e.printStackTrace();
}
channel.accept(null, new CompletionHandler<AsynchronousSocketChannel, Void>() {
@Override
public void completed(AsynchronousSocketChannel socket, Void attachment) {
channel.accept(attachment, this);
ByteBuffer byteBuffer = ByteBuffer.allocate(64);
socket.read(byteBuffer);
byteBuffer.flip();
System.out.println(new String(byteBuffer.array()));
}
@Override
public void failed(Throwable exc, Void attachment) {
System.out.println("建立通信失败");
}
});
}
public static void main(String[] args) {
new TestServer(9000);
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
//TestClient.java
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
public class TestClient {
public static void main(String[] args) throws Exception {
AsynchronousSocketChannel channel = AsynchronousSocketChannel.open();
channel.connect(new InetSocketAddress("127.0.0.1", 9000));
ByteBuffer buffer = ByteBuffer.allocate(64);
buffer.put("hello".getBytes());
buffer.flip();
channel.write(buffer);
}
}