zoukankan      html  css  js  c++  java
  • 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本身不管被关闭。

  • 相关阅读:
    django 标签的使用
    django(models)视图与html 简单的操作
    Django 简单的使用
    安全性测试计划
    常用缩写
    ADB 基本命令整理
    kindle升级测试
    虚拟机的类加载机制
    垃圾收集器与内存分配策略之篇三:理解GC日志和垃圾收集器参数总结
    垃圾收集器与内存分配策略之篇二:垃圾收集器
  • 原文地址:https://www.cnblogs.com/jerrice/p/7121637.html
Copyright © 2011-2022 走看看