美文网首页
nio小记 - 轮询SelectionKey为什么要删除

nio小记 - 轮询SelectionKey为什么要删除

作者: eqgao | 来源:发表于2018-01-19 23:27 被阅读320次
     // 轮询访问selector
            while (true) {
                // 当注册的事件到达时,方法返回;否则,该方法会一直阻塞
                // 多路复用  Reactor模型
                this.selector.select();
                // 无论是否有读写事件发生,selector每隔1s被唤醒一次  
                 //this.selector.select(1000);
                 //this.selector.selectNow();
                // 获得selector中选中的项的迭代器,选中的项为注册的事件
                Iterator<?> iteratorKey = this.selector.selectedKeys().iterator();
                while (iteratorKey.hasNext()) {
                    SelectionKey selectionKey = (SelectionKey) iteratorKey.next();
                    // 删除已选的key,以防重复处理
                    iteratorKey.remove();
                    
                    new Thread(new Runnable() {
                        
                        @Override
                        public void run() {
                            // 处理请求
                            try {
                                handler(selectionKey);
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                            
                        }
                    });
                    
                }
            }
    
    • Selector.select()取出事件集中的全部事件,如果不删除,在下次轮询的时候,调用Selector.select()会取出旧的事件集,导致重复处理

    相关文章

      网友评论

          本文标题:nio小记 - 轮询SelectionKey为什么要删除

          本文链接:https://www.haomeiwen.com/subject/gafzoxtx.html