【Java】 BIO与NIO以及AIO分析
一.BIO与NIO以及AIO的概念
BIO是同步阻塞式的IO
NIO是同步非阻塞的IO (NIO1.0,JDK1.4)
AIO是非同步非阻塞的IO(NIO2.0,JDK1.7)
二.BIO简单分析
1.简单分析
BIO是阻塞的IO,原因在于accept和read会阻塞。所以单线程的BIO是无法处理并发的。
2.案例
服务端:
public class BioServer {
public static void main(String[] args) throws IOException {//在开发中不要直接抛出去,有可能出现异常导致连接未关闭
ServerSocket serverSocket = new ServerSocket();
serverSocket.bind(new InetSocketAddress("127.0.0.1",9999));
byte[] b = new byte[1024];
StringBuilder sb = new StringBuilder();
System.out.println("服务端正在等待连接......");
Socket socketAccept = serverSocket.accept();//这里会阻塞
System.out.println("有客户端连接成功");
while (true){
System.out.println("等待消息......");
int read = socketAccept.getInputStream().read(b);//这里会阻塞
System.out.println("共读取了"+read+"个字节");
String str = new String(b);
sb.append(str);
System.out.println("读取的数据内容为: " + sb);
}
}
}
客户端:
public class BioClient {
public static void main(String[] args) throws IOException {
Socket socket = new Socket();
Scanner scanner = new Scanner(System.in);
socket.connect(new InetSocketAddress("127.0.0.1",9999));
while(true){
System.out.println("请输入内容");
String next = scanner.next();
socket.getOutputStream().write(next.getBytes());
}
}
}
测试如下:

3.多线程下的BIO
多线程的BIO是可以处理并发的,但频繁的创建线程,运行线程以及销毁线程无疑是非常消耗资源的(即便可以使用线程池限制线程数量,但海量并发时,BIO的方式效率相比于NIO还是太低了)
下面是一个多线程的BIO案例:
服务端:
public class BioServerMultiThread {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket();
serverSocket.bind(new InetSocketAddress("127.0.0.1",9999));
System.out.println("服务端正在等待连接......");
while (true){
Socket socketAccept = serverSocket.accept();//这里会阻塞
System.out.println("有客户端连接成功");
new Thread(new Runnable() {
@Override
public void run() {
try{
System.out.println("等待消息......");
String msg = "";
while (true){
byte[] b = new byte[1024];
int len = socketAccept.getInputStream().read(b);
if (len < 0){
continue;
}
msg = new String(b,0,len);
System.out.println(msg);
}
}catch (Exception e){
e.printStackTrace();
}
}
}).start();
}
}
}
客户端(创建多个客户端,代码相同):
public class BioClient1 {
public static void main(String[] args) throws IOException {
Socket socket = new Socket();
Scanner scanner = new Scanner(System.in);
socket.connect(new InetSocketAddress("127.0.0.1",9999));
String className = "这是来自"+Thread.currentThread().getStackTrace()[1].getClassName()+"的消息";
while(true){
System.out.println("请输入内容");
String next = scanner.next();
socket.getOutputStream().write(className.getBytes());
socket.getOutputStream().write(next.getBytes());
}
}
}
测试如下:

三.NIO简单分析
NIO是非阻塞IO,其原因在于数据准备就绪后,由选择器通知给服务端,而在数据准备完毕之前,服务器无需等待。
1.缓冲区
在BIO操作中,所有的数据都是以流的形式操作的,而在NIO中,则都是使用缓冲区来操作。
NIO中的缓冲区是Buffer类,它是java.nio包下的一个抽象类,详情可以查看JDK的API文档,例如下图

打开Buffer类,可以看到如下图(其中带有的方法可以查看JDK文档)

2.直接缓冲区和非直接缓冲区
直接缓冲区是指将缓冲区建立在物理内存中,通过allocateDirect方法建立(效率高,但不安全)
非直接缓冲区是指将缓冲区建立在JVM中,通过allocate方法建立(效率低,但安全)
3.管道
管道是NIO中传输数据的桥梁,它是java.nio包下的一个接口,若需查看其详细信息可以参考JDK的API文档,例如下图

4.使用NIO实现文件拷贝两种方式案例
直接缓冲区的方式:
@Test
public void test1() throws IOException {
long statTime=System.currentTimeMillis();
//创建管道
FileChannel inChannel= FileChannel.open(Paths.get("E://test/aaa.txt"), StandardOpenOption.READ);
FileChannel outChannel= FileChannel.open(Paths.get("E://test/bbb.txt"), StandardOpenOption.READ,StandardOpenOption.WRITE, StandardOpenOption.CREATE);
//定义映射文件
MappedByteBuffer inMappedByte = inChannel.map(FileChannel.MapMode.READ_ONLY,0, inChannel.size());
MappedByteBuffer outMappedByte = outChannel.map(FileChannel.MapMode.READ_WRITE,0, inChannel.size());
//直接对缓冲区操作
byte[] dsf=new byte[inMappedByte.limit()];
inMappedByte.get(dsf);
outMappedByte.put(dsf);
inChannel.close();
outChannel.close();
long endTime=System.currentTimeMillis();
System.out.println("操作直接缓冲区耗时时间:"+(endTime-statTime));
}
非直接缓冲区的方式:
@Test
public void test2() throws IOException {
long statTime=System.currentTimeMillis();
// 读入流
FileInputStream fst = new FileInputStream("E://test/bbb.txt");
// 写入流
FileOutputStream fos = new FileOutputStream("E://test/ccc.txt");
// 创建通道
FileChannel inChannel = fst.getChannel();
FileChannel outChannel = fos.getChannel();
// 分配指定大小缓冲区
ByteBuffer buf = ByteBuffer.allocate(1024);
while (inChannel.read(buf) != -1) {
// 开启读取模式
buf.flip();
// 将数据写入到通道中
outChannel.write(buf);
buf.clear();
}
// 关闭通道 、关闭连接
inChannel.close();
outChannel.close();
fos.close();
fst.close();
long endTime=System.currentTimeMillis();
System.out.println("操作非直接缓冲区耗时时间:"+(endTime-statTime));
}
5.选择器(Selector)
它是Java NIO核心组件中的一个,用于检查一个或多个NIO Channel(通道)的状态是否处于可读、可写。如此可以实现单线程管理多个channels,也就是可以管理多个网络链接。使用Selector的好处在于: 使用更少的线程来就可以来处理通道了, 相比使用多个线程,避免了线程上下文切换带来的开销。详细用法可以参考JDK的API文档

NIO服务端实现同步非阻塞代码如下
public class NioServer {
public static void main(String[] args) throws IOException {
ServerSocketChannel ssc = ServerSocketChannel.open();
ssc.socket().bind(new InetSocketAddress("127.0.0.1", 9999));
ssc.configureBlocking(false);//设置成非阻塞模型
System.out.println("server started, listening on :" + ssc.getLocalAddress());
Selector selector = Selector.open();
ssc.register(selector, SelectionKey.OP_ACCEPT);
while(true) {
selector.select();
Set<SelectionKey> keys = selector.selectedKeys();
Iterator<SelectionKey> it = keys.iterator();
while(it.hasNext()) {
SelectionKey key = it.next();
it.remove();
handle(key);
}
}
}
private static void handle(SelectionKey key) {
if(key.isAcceptable()) {
try {
ServerSocketChannel ssc = (ServerSocketChannel) key.channel();
SocketChannel sc = ssc.accept();
sc.configureBlocking(false);
sc.register(key.selector(), SelectionKey.OP_READ );
} catch (IOException e) {
e.printStackTrace();
} finally {
}
} else if (key.isReadable()) {
SocketChannel sc = null;
try {
sc = (SocketChannel)key.channel();
ByteBuffer buffer = ByteBuffer.allocate(512);
buffer.clear();
int len = sc.read(buffer);
if(len != -1) {
System.out.println(new String(buffer.array(), 0, len));
}
ByteBuffer bufferToWrite = ByteBuffer.wrap("HelloClient".getBytes());
sc.write(bufferToWrite);
} catch (IOException e) {
e.printStackTrace();
} finally {
if(sc != null) {
try {
sc.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
}
四.AIO简单分析
AIO(NIO2.0)和 NIO的主要区别是前者是异步的,而后者是同步的。(NIO每隔一段时间用Selector轮询查看是否有事件发生,而AIO是在等有事件发生的时候,Selector通知服务端)
与NIO不同,当进行读写操作时,AIO只须直接调用API的read或write方法即可。这两种方法均为异步的,对于读操作而言,当有流可读取时,操作系统会将可读的流传入read方法的缓冲区,并通知应用程序;对于写操作而言,当操作系统将write方法传递的流写入完毕时,操作系统主动通知应用程序。 即可以理解为,read/write方法都是异步的,完成后会主动调用回调函数。
AIO服务端简单案例如下
public class Server {
public static void main(String[] args) throws Exception {
final AsynchronousServerSocketChannel serverChannel = AsynchronousServerSocketChannel.open()
.bind(new InetSocketAddress(8888));
serverChannel.accept(null, new CompletionHandler<AsynchronousSocketChannel, Object>() {
@Override
public void completed(AsynchronousSocketChannel client, Object attachment) {
serverChannel.accept(null, this);
try {
System.out.println(client.getRemoteAddress());
ByteBuffer buffer = ByteBuffer.allocate(1024);
client.read(buffer, buffer, new CompletionHandler<Integer, ByteBuffer>() {
@Override
public void completed(Integer result, ByteBuffer attachment) {
attachment.flip();
System.out.println(new String(attachment.array(), 0, result));
client.write(ByteBuffer.wrap("HelloClient".getBytes()));
}
@Override
public void failed(Throwable exc, ByteBuffer attachment) {
exc.printStackTrace();
}
});
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void failed(Throwable exc, Object attachment) {
exc.printStackTrace();
}
});
}
}
【Java】 BIO与NIO以及AIO分析的更多相关文章
- [转帖]JAVA BIO与NIO、AIO的区别(这个容易理解)
JAVA BIO与NIO.AIO的区别(这个容易理解) https://blog.csdn.net/ty497122758/article/details/78979302 2018-01-05 11 ...
- Java BIO、NIO与AIO的介绍(学习过程)
Java BIO.NIO与AIO的介绍 因为netty是一个NIO的框架,所以在学习netty的过程中,开始之前.针对于BIO,NIO,AIO进行一个完整的学习. 学习资源分享: Netty学习:ht ...
- Java BIO、NIO、AIO 学习(转)
转自 http://stevex.blog.51cto.com/4300375/1284437 先来个例子理解一下概念,以银行取款为例: 同步 : 自己亲自出马持银行卡到银行取钱(使用同步IO时,Ja ...
- Java BIO、NIO、AIO 学习
正在学习<大型网站系统与JAVA中间件实践>,发现对BIO.NIO.AIO的概念很模糊,写一篇博客记录下来.先来说个银行取款的例子: 同步 : 自己亲自出马持银行卡到银行取钱(使用同步IO ...
- JAVA BIO与NIO、AIO的区别
IO的方式通常分为几种,同步阻塞的BIO.同步非阻塞的NIO.异步非阻塞的AIO. 一.BIO 在JDK1.4出来之前,我们建立网络连接的时候采用BIO模式,需要先在服务端启动一个ServerSock ...
- Java BIO、NIO、AIO 原理
先来个例子理解一下概念,以银行取款为例: 同步 : 自己亲自出马持银行卡到银行取钱(使用同步IO时,Java自己处理IO读写). 异步 : 委托一小弟拿银行卡到银行取钱,然后给你(使用异步IO时,Ja ...
- Java BIO、NIO、AIO 基础,应用场景
Java对BIO.NIO.AIO的支持: Java BIO : 同步并阻塞,服务器实现模式为一个连接一个线程,即客户端有连接请求时服务器端就需要启动一个线程进行处理,如果这个连接不做任何事情会造成不必 ...
- 【转】JAVA BIO与NIO、AIO的区别
Java中IO的模型分为三种,同步阻塞的BIO.同步非阻塞的NIO.异步非阻塞的AIO. BIO[同步阻塞] 在JDK1.4出来之前,我们建立网络连接的时候采用BIO模式,需要先在服务端启动一个Ser ...
- Java BIO、NIO、AIO
同步与异步 同步与异步的概念, 关注的是 消息通信机制 同步是指发出一个请求, 在没有得到结果之前该请求就不返回结果, 请求返回时, 也就得到结果了. 比如洗衣服, 把衣服放在洗衣机里, 没有洗好之前 ...
随机推荐
- Android 中更新 UI 的四种方式
runOnUiThread handler 的 post handler 的 sendMessage View 自身的 post
- css3属性clip
clip 属性定义了元素的哪一部分是可见的.clip 属性只适用于 position:absolute 的元素. rect(<top>, <right>, <bottom ...
- HmacSha1加密-java
package com.test; import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; import org.apache ...
- Java线程池(Callable+Future模式)
转: Java线程池(Callable+Future模式) Java线程池(Callable+Future模式) Java通过Executors提供四种线程池 1)newCachedThreadPoo ...
- AOP获取方法注解实现动态切换数据源
AOP获取方法注解实现动态切换数据源(以下方式尚未经过测试,仅提供思路) ------ 自定义一个用于切换数据源的注解: package com.xxx.annotation; import org. ...
- VLAN和VXLAN的区别
VLAN ·概况 VLAN (Virtual Local Area Network)意为虚拟局域网,是在交换机实现过程中涉及到的概念,由802.1Q标准所定义.由于交换机是工作在链路层的网络设备,连接 ...
- element-ui分页当前在哪一页,刷新页面保留当前分页
- KDE-解决.docx .xlsx .pptx文档默认由Ark打开的问题
安装KDE后,默认的压缩解压程序变成了Ark,并且原来默认用WPS Office打开的.docx .xlsx .pptx文档,从文件管理器双击打开时,也变成了用Ark打开. 查了下网上的资料,可通过如 ...
- NSubstitute.Analyzers检测NSubstitute用法冲突
NSubstitute是一个.Net环境使用的,简洁,语法友好的Mock库.语法简洁的缺点是有一些失败的用法很难察觉和检测.比如试图mock一个非虚拟成员-NSubstitute不能看到这些成员所以不 ...
- 关于Java新手开发配置各种环境可能会遇到的的坑
一.软件的安装 虽然国内的软件都支持中文目录安装,部分国外软件也支持,但是作为一名合格的程序开发者,必须做到以下几点 Windows下开发软件的安装目录和环境变量中永远不要包含中文字符,包括汉字[]. ...