• JAVA NIO中selectedKeys返回的键集,对其中的SelectionKey执行操作之后,是否需要在selectedKeys()中对其执行remove 操作


    今天一个东西需要用到java nio的东西。在网上查了一下资料。之前看过这部分的内容,但好长一段时间没有用,也就忘得七七八八了。如今是温故而知新,但其中遇到了些疑问:

    先贴上代码吧:

    public static void main(String[] args) throws Exception{
    		
    		Thread sh=new Thread(new Runnable() {
    			public void run(){
    				try{
    					ServerSocket ss=new ServerSocket(3000);
    					Socket client=ss.accept();
    					OutputStream os=client.getOutputStream();
    					while(true){
    						os.write("Helloworld".getBytes());
    						Thread.sleep(1000);
    					}
    				}catch(Exception e){
    					e.printStackTrace();
    				}
    				
    			}
    		});
    		sh.start();
    		
    		
    		SocketChannel sc=SocketChannel.open();
    		sc.socket().connect(new InetSocketAddress("localhost",3000) );
    		sc.configureBlocking(false);
    		Selector selector=Selector.open();
    		sc.register(selector,SelectionKey.OP_READ);
    		
    		ByteBuffer byteBuffer=ByteBuffer.allocate(1000);
    		while(true){
    			if(selector.select()>0){
    				Set<SelectionKey> sks=selector.selectedKeys();
    				Iterator<SelectionKey> it = sks.iterator();
    				while(it.hasNext()){
                            SelectionKey key=it.next(); if(key.isReadable()){ System.out.println("is Readable() "); SocketChannel isc=(SocketChannel)key.channel(); isc.read(byteBuffer); } it.remove(); } } System.out.println("return from select() "); } }

      

    关于是否需要it.remove()这一行呢。

    按照上面运行的结果:

    is Readable() 
    return from select() 
    is Readable() 
    return from select() 
    is Readable() 
    return from select() 
    is Readable() 
    return from select()
    

    然后把sks.remove(key)这一行注释掉,再次运行:

    is Readable()
    return from select() 
    return from select() 
    return from select() 
    return from select() 
    return from select() 
    return from select() 
    return from select() 
    return from select() 
    return from select() 
    return from select() 
    return from select() 
    return from select() 
    return from select() 
    ...

    说明了,如果不对已经处理完的SelectionKey在selectedKeys中执行remove操作的话。下一次select()操作将会直接返回,但其返回的值是0。Selector类型于“水平触发”,但与水平触发不一样的是,下一次Selector.select的时候,并不会返回上一次没有remove掉的键集。

  • 相关阅读:
    python3中的匿名函数
    python3拆包、元组、字典
    python3函数中的不定长参数
    python3中的缺省参数和命名参数
    python3字符串的常见操作
    用python使用Mysql数据库
    Git常用命令
    Linux下配置Nginx(在root的/etc/rc.local里配置开机启动功能http://tengine.taobao.org/)
    大数据项目中js中代码和java中代码(解决Tomcat打印日志中文乱码)
    java中时间
  • 原文地址:https://www.cnblogs.com/mosmith/p/4449875.html
Copyright © 2020-2023  润新知