每天一道面试题@第六天

1. 内部类了解吗?匿名内部类了解吗?

Java内部类

其他 常见面试问题

(1)为什么需要内部类?

封装性:将仅被外部类使用的逻辑隐藏起来。

多继承模拟:Java 单继承,通过内部类实现多接口的灵活组合。

(2)成员内部类和静态内部类的区别?

成员内部类依赖外部类实例,可访问所有成员;静态内部类独立,仅访问静态成员。

(3)匿名内部类能否有构造函数?

不能,因为无类名,但可通过实例初始化块({})模拟初始化逻辑。

(4)如何避免内部类导致的内存泄漏?

使用静态内部类,或及时解除对外部类实例的强引用。

内存泄漏的原因:非静态内部类隐式持有外部类的引用,若内部类对象生命周期过长(如被静态变量引用),会导致外部类无法被回收。


2. BIO、NIO、AIO 有什么区别?

(1)模型与阻塞机制

  • BIO (Blocking I/O)

    • 同步阻塞:I/O操作会阻塞线程直到完成。例如,read()会一直等待数据就绪,线程无法执行其他任务。

    • 线程模型:每个连接需要一个独立线程处理,高并发时线程数激增,资源消耗大。

  • NIO (Non-blocking I/O 或 New I/O)

    • 同步非阻塞:线程发起I/O操作后立即返回,通过轮询(如Selector)检查数据状态,避免线程阻塞。

    • 多路复用:单线程可管理多个通道(Channel),通过事件驱动机制(如连接、读、写事件)高效处理高并发连接。

  • AIO (Asynchronous I/O)

    • 异步非阻塞:I/O操作由操作系统完成后回调通知应用,线程无需等待或轮询

    • 回调机制:通过CompletionHandlerFuture实现异步处理,减少线程资源占用。

(2)核心组件

  • BIO:基于流(InputStream/OutputStream)实现,简单直观

  • NIO:核心为Channel(通道)、Buffer(缓冲区)、Selector(选择器),支持非阻塞和事件驱动。

  • AIO:通过AsynchronousChannel及相关类实现,依赖操作系统底层异步支持。

(3)性能与适用场景

  • BIO

    • 适用场景:连接数少且固定的场景(如传统请求-响应应用)。

    • 缺点:线程数随连接线性增长,高并发时性能急剧下降。

  • NIO

    • 适用场景:高并发、短连接或长连接需高效处理的场景(如即时通讯、游戏服务器)。

    • 优点:通过多路复用提升吞吐量,但编程复杂度较高(需处理事件循环、缓冲区管理)。

  • AIO

    • 适用场景:长耗时、高吞吐量的I/O操作(如大文件读写、高并发网络服务)。

    • 优点:减少线程开销,但依赖操作系统支持,Linux平台实现可能受限。

(4) 编程复杂度

  • BIO:代码简单,但线程管理复杂。

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

public class BIOServer {
    public static void main(String[] args) {
        try (ServerSocket serverSocket = new ServerSocket(8888)) {
            System.out.println("Server started, listening on port 8888");
            while (true) {
                Socket socket = serverSocket.accept();
                System.out.println("New client connected");
                new Thread(() -> {
                    try (InputStream inputStream = socket.getInputStream()) {
                        byte[] buffer = new byte[1024];
                        int length;
                        while ((length = inputStream.read(buffer)) != -1) {
                            System.out.println(new String(buffer, 0, length));
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }).start();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
  • NIO:需理解非阻塞逻辑、事件循环和缓冲区,复杂度较高。

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 NIOServer {
    public static void main(String[] args) {
        try (ServerSocketChannel serverSocketChannel = ServerSocketChannel.open()) {
            serverSocketChannel.socket().bind(new InetSocketAddress(8888));
            serverSocketChannel.configureBlocking(false);

            Selector selector = Selector.open();
            serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);

            System.out.println("Server started, listening on port 8888");

            while (true) {
                selector.select();
                Set<SelectionKey> selectedKeys = selector.selectedKeys();
                Iterator<SelectionKey> keyIterator = selectedKeys.iterator();

                while (keyIterator.hasNext()) {
                    SelectionKey key = keyIterator.next();

                    if (key.isAcceptable()) {
                        ServerSocketChannel serverChannel = (ServerSocketChannel) key.channel();
                        SocketChannel socketChannel = serverChannel.accept();
                        socketChannel.configureBlocking(false);
                        socketChannel.register(selector, SelectionKey.OP_READ);
                        System.out.println("New client connected");
                    } else if (key.isReadable()) {
                        SocketChannel socketChannel = (SocketChannel) key.channel();
                        ByteBuffer buffer = ByteBuffer.allocate(1024);
                        int length = socketChannel.read(buffer);
                        if (length > 0) {
                            buffer.flip();
                            byte[] data = new byte[buffer.remaining()];
                            buffer.get(data);
                            System.out.println(new String(data));
                        }
                    }
                    keyIterator.remove();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
  • AIO:异步回调模型需适应,但逻辑较NIO更简洁。

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 AIOServer {
    public static void main(String[] args) {
        try (AsynchronousServerSocketChannel serverSocketChannel = AsynchronousServerSocketChannel.open()) {
            serverSocketChannel.bind(new InetSocketAddress(8888));
            System.out.println("Server started, listening on port 8888");

            serverSocketChannel.accept(null, new CompletionHandler<AsynchronousSocketChannel, Object>() {
                @Override
                public void completed(AsynchronousSocketChannel socketChannel, Object attachment) {
                    serverSocketChannel.accept(null, this);
                    try {
                        ByteBuffer buffer = ByteBuffer.allocate(1024);
                        socketChannel.read(buffer, buffer, new CompletionHandler<Integer, ByteBuffer>() {
                            @Override
                            public void completed(Integer result, ByteBuffer buffer) {
                                if (result > 0) {
                                    buffer.flip();
                                    byte[] data = new byte[buffer.remaining()];
                                    buffer.get(data);
                                    System.out.println(new String(data));
                                }
                            }

                            @Override
                            public void failed(Throwable exc, ByteBuffer buffer) {
                                try {
                                    socketChannel.close();
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }
                            }
                        });
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

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

            // 防止主线程退出
            Thread.sleep(Long.MAX_VALUE);
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

一碗谦谦粉

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

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

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

打赏作者

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

抵扣说明:

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

余额充值