码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2015-04-23 13:08:06      阅读:451      评论:0      收藏:0      [点我收藏+]

标签:

今天一个东西需要用到java nio的东西。在网上查了一下资料,发现有Apache的Mina,Netty等,感觉JDK中带的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();
				
				for(SelectionKey key:sks){
					if(key.isReadable()){
						System.out.println("is Readable() ");
						SocketChannel isc=(SocketChannel)key.channel();
						isc.read(byteBuffer);
					}
					sks.remove(key);
				}
			}
			System.out.println("return from select() ");
		}
	}

  

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

按照上面运行的结果:

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在selectedKyes中执行remove操作的话。下一次select()操作将会直接返回,但其返回的值是0

 

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

标签:

原文地址:http://www.cnblogs.com/mosmith/p/4449875.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!