1 channel.register(selector, SelectionKey.OP_READ) 和 key.interestOps(SelectionKey.OP_WRITE)有什么区别?
首先看看register源代码:
public final SelectionKey register(Selector sel, int ops, Object att) throws ClosedChannelException
{
if (!isOpen()) throw new ClosedChannelException();
if ((ops & ~validOps()) != 0)
throw new IllegalArgumentException();
synchronized (regLock)
{
if (blocking) throw new IllegalBlockingModeException();
SelectionKey k = findKey(sel);
if (k != null)
{
k.interestOps(ops); k.attach(att);
}
if (k == null)
{ // New
registration k = ((AbstractSelector)sel).register(this, ops, att);
addKey(k);
}
return k;
}
}
从红色代码只注册会判断每次是否已经注册过,那么在实际程序开发中,当一件事情已经注册过时,下次通过调用 key.interestOps()来进行感兴趣事件的切换