MST

星途 面试题库

面试题:Java中Selector高效轮询的基础配置

在Java NIO中,简述Selector实现高效轮询的基本配置步骤,包括如何创建Selector、注册通道以及设置通道为非阻塞模式。
37.4万 热度难度
编程语言Java

知识考点

AI 面试

面试题答案

一键面试
  1. 创建Selector

    Selector selector = Selector.open();
    
  2. 获取通道并设置为非阻塞模式: 以SocketChannel为例,

    SocketChannel socketChannel = SocketChannel.open();
    socketChannel.configureBlocking(false);
    
  3. 注册通道到Selector并指定感兴趣的事件

    socketChannel.register(selector, SelectionKey.OP_READ);
    

    上述代码中SelectionKey.OP_READ表示对读事件感兴趣,还可以是SelectionKey.OP_WRITE(写事件)、SelectionKey.OP_CONNECT(连接事件)、SelectionKey.OP_ACCEPT(接收连接事件)等。

    对于ServerSocketChannel,同样先获取通道并设置为非阻塞模式:

    ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
    serverSocketChannel.configureBlocking(false);
    serverSocketChannel.bind(new InetSocketAddress(8080));
    serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
    

    这里注册OP_ACCEPT事件用于监听客户端连接。