Java NIO(三)

07. Java NIO Selector选择器

Selector用于检查一个或多个NIO Channel的状态是否处于可读、可写。如此可以实现单线程管理多个channels,也就是可以管理多个网络链接。

创建Selector : Selector selector = Selector.open();

注册Channel到Selector上 : 

channel.configureBlocking(false); SelectionKey key = channel.register(selector, SelectionKey.OP_READ);


Channel必须是非阻塞的。所以FileChannel不适用Selector,因为FileChannel不能切换为非阻塞模式。Socket channel可以正常使用。

四种就绪状态用SelectionKey中的常量表示如下:

  1. SelectionKey.OP_CONNECT 连接就绪
  2. SelectionKey.OP_ACCEPT  接收就绪
  3. SelectionKey.OP_READ
  4. SelectionKey.OP_WRITE

如果对多个事件感兴趣可利用位的或运算结合多个常量,比如:

int interestSet = SelectionKey.OP_READ | SelectionKey.OP_WRITE;


SelectionKey's 比较有价值的属性:

1. 感兴趣集合:int interestSet = selectionKey.interestOps();

2.Ready Set: int readySet = selectionKey.readyOps();

3. Channel + Selector : Channel channel = selectionKey.channel();  Selector selector = selectionKey.selector()

4. Attaching Objects :给SelectionKey 附加一个Object,增加Channel相关的附加信息

selectionKey.attach(theObject);

Object attachedObj = selectionKey.attachment();

Selector.wakeup() 由于调用select而被阻塞的线程,可以通过调用Selector.wakeup()来唤醒

Selector.close() 当操作Selector完毕后,需要调用close方法。close的调用会关闭Selector并使相关的SelectionKey都无效。channel本身不管被关闭。

原文地址:https://www.cnblogs.com/jerrice/p/7121637.html