阻塞IO、非阻塞IO、异步IO的区别

1. 阻塞IO (Blocking IO)

在传统的阻塞IO模型中,示例中的 serverSocket.accept(),这是一个阻塞调用,意味着调用线程将被挂起直到一个连接请求到达。这是典型的阻塞行为。

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class BlockingIOServer {
    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = new ServerSocket(8080);
        System.out.println("Server started on port 8080");

        while (true) {
            Socket clientSocket = serverSocket.accept();
            // 注意:accept() 是一个阻塞调用
            new Thread(() -> {
                try {
                    byte[] buffer = new byte[1024];
                    int bytesRead = clientSocket.getInputStream().read(buffer);
                    // read() 也是一个阻塞调用
                    if (bytesRead > 0) {
                        String message = new String(buffer, 0, bytesRead);
                        System.out.println("Received: " + message);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    try {
                        clientSocket.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        }
    }
}

2. 非阻塞IO (Non-Blocking IO)

在Java中,你可以使用 NIO(Non-blocking IO)库来实现非阻塞IO。例如,你使用 SelectorSelectableChannel 来监听多个 SocketChannel 的可读状态。当没有数据可读时,你的程序不会被阻塞,而是可以立即返回并处理其他任务,只有当数据真正到达时,你才会被通知去读取。

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

public class NonBlockingIOServer {
    public static void main(String[] args) throws IOException {
        Selector selector = Selector.open();
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.configureBlocking(false);
        serverSocketChannel.socket().bind(new InetSocketAddress(8080));
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
        
        System.out.println("Server started on port 8080");
        
        while (true) {
            if (selector.select() == 0) {//这里会阻塞,等待Channel事件发生
                continue; // no events ready for processing
            }
            
            Set<SelectionKey> keys = selector.selectedKeys();
            Iterator<SelectionKey> iterator = keys.iterator();
            
            while (iterator.hasNext()) {
                SelectionKey key = iterator.next();
                iterator.remove();
                
                if (key.isAcceptable()) {
                    ServerSocketChannel ssc = (ServerSocketChannel) key.channel();
                    SocketChannel sc = ssc.accept();//这里是非阻塞
                    sc.configureBlocking(false);
                    sc.register(selector, SelectionKey.OP_READ);
                } else if (key.isReadable()) {
                    SocketChannel sc = (SocketChannel) key.channel();
                    ByteBuffer buffer = ByteBuffer.allocate(1024);
                    int bytesRead = sc.read(buffer);//这里也是非阻塞
                    if (bytesRead > 0) {
                        buffer.flip();
                        byte[] data = new byte[buffer.remaining()];
                        buffer.get(data);
                        System.out.println("Received: " + new String(data));
                    }
                }
            }
        }
    }
}

在这个示例中,selector.select()serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT) 结合使用。serverSocketChannel 已经配置为非阻塞模式,这意味着 serverSocketChannel.accept() 本身不会阻塞当前线程。然而,selector.select() 方法是一个阻塞调用,它会阻塞直到至少一个通道上的事件准备好被处理。当调用 selector.select() 时,线程将等待至少一个注册的通道有事件发生(例如,一个连接请求到达或数据可读)。 

3. 异步IO (Asynchronous IO)

异步IO是最先进的IO模型,它不仅不会阻塞线程,而且还会在IO操作完成后主动通知应用程序。也就是说,你只需要告诉操作系统你想做什么,然后继续执行其他任务,当IO操作完成时,操作系统会通过回调函数、事件通知等方式告知你。

示例:

在这个示例中,serverChannel.accept() 是异步调用,它使用了 CompletionHandler。这意味着调用线程不会被阻塞,而是会立即返回。当一个连接请求到达时,CompletionHandlercompleted 方法将在异步线程池中的某个线程上被调用。因此,serverChannel.accept(null, new CompletionHandler<...>) 在调用时不会阻塞当前线程。

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousChannelGroup;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class AsyncIOServer {
    public static void main(String[] args) throws IOException {
        ExecutorService threadPool = Executors.newFixedThreadPool(5);
        AsynchronousChannelGroup group = AsynchronousChannelGroup.withThreadPool(threadPool);
        AsynchronousServerSocketChannel serverChannel = AsynchronousServerSocketChannel.open(group).bind(new java.net.InetSocketAddress(8080));
        
        System.out.println("Server started on port 8080");
        
        serverChannel.accept(null, new CompletionHandler<AsynchronousSocketChannel, Void>() {
            @Override
            public void completed(AsynchronousSocketChannel result, Void attachment) {
                ByteBuffer buffer = ByteBuffer.allocate(1024);
                result.read(buffer, buffer, new CompletionHandler<Integer, ByteBuffer>() {
                    @Override
                    public void completed(Integer result, ByteBuffer attachment) {
                        if (result > 0) {
                            attachment.flip();
                            byte[] data = new byte[attachment.remaining()];
                            attachment.get(data);
                            System.out.println("Received: " + new String(data));
                            attachment.clear();
                            result.read(attachment, attachment, this);
                        } else {
                            result.close();
                        }
                    }

                    @Override
                    public void failed(Throwable exc, ByteBuffer attachment) {
                        exc.printStackTrace();
                    }
                });
                serverChannel.accept(null, this);
            }

            @Override
            public void failed(Throwable exc, Void attachment) {
                exc.printStackTrace();
            }
        });
    }
}

总结一下,阻塞IO会阻止线程直到IO操作完成;非阻塞IO允许线程在没有数据可处理时立即返回;而异步IO则完全不需要线程等待,而是通过回调或事件通知来处理完成的IO操作。

  • 5
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Addison_Wang

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值