之前说过,同步指的按顺序一次完成一个任务,直到前一个任务完成并有了结果以后,才能再执行后面的任务。而异步指的是前一个任务结束后,并不等待任务结果,而是继续执行后一个任务,在所有任务都「执行」完后,通过任务的回调函数去获得结果。所以异步使得应用性能有了极大的提高。为了更加生动地说明什么是异步,可以来做个实验:
/**
* AIO客户端
*
* @author xiangwang
*/
public class AioClient {
public void start() throws IOException, InterruptedException {
AsynchronousSocketChannel channel = AsynchronousSocketChannel.open();
if (channel.isOpen()) {
// socket接收缓冲区recbuf大小
channel.setOption(StandardSocketOptions.SO_RCVBUF, 128 * 1024);
// socket发送缓冲区recbuf大小
channel.setOption(StandardSocketOptions.SO_SNDBUF, 128 * 1024);
// 保持长连接状态
channel.setOption(StandardSocketOptions.SO_KEEPALIVE, true);
// 连接到服务端
channel.connect(new InetSocketAddress(8080), null,
new AioClientHandler(channel));
// 阻塞主进程
for(;;) {
TimeUnit.SECONDS.sleep(1);
}
} else {
throw new RuntimeException("Channel not opened!");
}
}
public static void main(String[] args) throws IOException, InterruptedException {
new AioClient().start();
}
}
/**
* AIO客户端CompletionHandler
*
* @author xiangwang
*/
public class AioClientHandler implements CompletionHandler<Void, AioClient> {
private final AsynchronousSocketChannel channel;
private final CharsetDecoder decoder = Charset.defaultCharset().newDecoder();
private final BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
public AioClientHandler(AsynchronousSocketChannel channel) {
this.channel = channel;
}
@Override
public void failed(Throwable exc, AioClient attachment) {
throw new RuntimeException("channel not opened!");
}
@Override
public void completed(Void result, AioClient attachment) {
System.out.println("send message to server: ");
try {
// 将输入内容写到buffer
String line = input.readLine();
channel.write(ByteBuffer.wrap(line.getBytes()));
// 在操作系统中的Java本地方法native已经把数据写到了buffer中
// 这里只需要一个缓冲区能接收就行了
ByteBuffer buffer = ByteBuffer.allocate(1024);
while (channel.read(buffer).get() != -1) {
buffer.flip();
System.out.println("from server: " + decoder.decode(buffer).toString());
if (buffer.hasRemaining()) {
buffer.compact();
} else {
buffer.clear();
}
// 将输入内容写到buffer
line = input.readLine();
channel.write(ByteBuffer.wrap(line.getBytes()));
}
} catch (IOException | InterruptedException | ExecutionException e) {
e.printStackTrace();
}
}
}
/**
* AIO服务端
*
* @author xiangwang
*/
public class AioServer {
public void start() throws InterruptedException, IOException {
AsynchronousServerSocketChannel channel = AsynchronousServerSocketChannel.open();
if (channel.isOpen()) {
// socket接受缓冲区recbuf大小
channel.setOption(StandardSocketOptions.SO_RCVBUF, 4 * 1024);
// 端口重用,防止进程意外终止,未释放端口,重启时失败
// 因为直接杀进程,没有显式关闭套接字来释放端口,会等待一段时间后才可以重新use这个关口
// 解决办法就是用SO_REUSEADDR
channel.setOption(StandardSocketOptions.SO_REUSEADDR, true);
channel.bind(new InetSocketAddress(