首页 > 技术文章 > Java NIO(一)水平触发

ralgo 2020-11-08 19:43 原文

1、NIO的selector是边缘触发还是水平触发?

水平触发,看下面这段代码:

public class Client1 {

	Selector selector;
	
	int writeEventTrigerCount = 0;
	public void run() throws IOException {
		selector = Selector.open();
		
		SocketChannel sc = SocketChannel.open();
		sc.configureBlocking(false);
		sc.register(selector, SelectionKey.OP_CONNECT);
		sc.connect(new InetSocketAddress("182.61.200.6", 80));
		
		while (true) {
			selector.select();
			Set<SelectionKey> selectionKeys = selector.selectedKeys();
			for (SelectionKey selectionKey : selectionKeys){
				if (!selectionKey.isValid()) {
					System.out.println(""+selectionKey+" is not valid");
				} else if (selectionKey.isConnectable()) {
					System.out.println(""+selectionKey+" connected");
					SocketChannel client = (SocketChannel)selectionKey.channel();
					client.finishConnect();
					
					selectionKey.interestOps(SelectionKey.OP_WRITE);
				} else if (selectionKey.isWritable()) {
					System.out.println(""+selectionKey+" writable");
					if (++writeEventTrigerCount > 10) {
						selectionKey.interestOps(SelectionKey.OP_READ);
					}
				} else if (selectionKey.isReadable()) {
					System.out.println(""+selectionKey+" readable");
				}
			}
		}
	}
	
	public static void main(String args[]) {
		Client1 client = new Client1();
		try {
			client.run();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

这代码输出为:
sun.nio.ch.SelectionKeyImpl@1d81eb93 connected
sun.nio.ch.SelectionKeyImpl@1d81eb93 writable
sun.nio.ch.SelectionKeyImpl@1d81eb93 writable
sun.nio.ch.SelectionKeyImpl@1d81eb93 writable
sun.nio.ch.SelectionKeyImpl@1d81eb93 writable
sun.nio.ch.SelectionKeyImpl@1d81eb93 writable
sun.nio.ch.SelectionKeyImpl@1d81eb93 writable
sun.nio.ch.SelectionKeyImpl@1d81eb93 writable
sun.nio.ch.SelectionKeyImpl@1d81eb93 writable
sun.nio.ch.SelectionKeyImpl@1d81eb93 writable
sun.nio.ch.SelectionKeyImpl@1d81eb93 writable
sun.nio.ch.SelectionKeyImpl@1d81eb93 writable

selector会一直报可写事件被触发,直到注销了写事件。所以java nio的selector是水平触发的。

推荐阅读