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。例如,你使用 Selector
和 SelectableChannel
来监听多个 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
。这意味着调用线程不会被阻塞,而是会立即返回。当一个连接请求到达时,CompletionHandler
的 completed
方法将在异步线程池中的某个线程上被调用。因此,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操作。