1. 内部类了解吗?匿名内部类了解吗?
其他 常见面试问题
(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操作由操作系统完成后回调通知应用,线程无需等待或轮询。
-
回调机制:通过
CompletionHandler
或Future
实现异步处理,减少线程资源占用。
-
(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();
}
}
}