这个可以从wakeup()的注释上找到答案:
/**
* Causes the first selection operation that has not yet returned to return
* immediately.
*
*
If another thread is currently blocked in an invocation of the
* {@link #select()} or {@link #select(long)} methods then that invocation
* will return immediately. If no selection operation is currently in
* progress then the next invocation of one of these methods will return
* immediately unless the {@link #selectNow()} method is invoked in the
* meantime. In any case the value returned by that invocation may be
* non-zero. Subsequent invocations of the {@link #select()} or {@link
* #select(long)} methods will block as usual unless this method is invoked
* again in the meantime.
*
*
Invoking this method more than once between two successive selection
* operations has the same effect as invoking it just once.
*
* @return This selector
*/
public abstract Selector wakeup();当B线程阻塞在select()或select(long)方法上时,A线程调用wakeup后,B线程会立刻返回。
如果没有线程阻塞在select()方法上,那么下一次某个线程调用select()或select(long)方法时,会立刻返回。
所以,当在Handler中完成SocketChannel注册后,显示的调用selector.wakeup()方法,虽然当前没有阻塞在select()上,但是会影响下一次调用select()。为什么在这里需要调用wakeup()方法?当注册新的Channel或事件时,希望能及时处理。