當調用selector.select()時會阻塞:
This method performs a blocking selection operation. It returns only after at least one channel is selected, this selector's wakeup method is invoked, or the current thread is interrupted, whichever comes first.
其返回值有可能為0:
The number of keys, possibly zero,
whose ready-operation sets were updated
另請見,解釋了select后返回值為0,但selector.selectedKeys()不為空:Java NIO Selector select() returns 0 although channels are ready
selector.selectedKeys()返回的Set<SelectionKey>需要刪除SelectionKey,原因請見:Why the key should be removed in `selector.selectedKeys().iterator()` in java nio?
另外,Set<SelectionKey>刪除SelectionKey需要使用iterator
,這個在第一個鏈接里也有原因