使用选择器和NIO频道时, 我可以使用一些(固定的)线程来处理每个可读密钥吗? (即每个频道每个可读密钥一个主题?)
例如: 而(真){
int readyChannels = m_selector.select(1000);
if (0 == readyChannels)
{
continue;
}
Set<SelectionKey> keys = m_selector.selectedKeys();
Iterator<SelectionKey> keyIterator = keys.iterator();
while(keyIterator.hasNext()) {
SelectionKey key = keyIterator.next();
keyIterator.remove();
if (key.isReadable()) {
...
**** WHAT CAN I WRITE HERE TO HANDLE EACH READABLE CHANNEL KEY ONCE ?
**** BECAUSE IF I OPEN NEW THREAD IT WILL NOT FINISH TO HANDLE THE KEY AND I WILL GET
**** TO THIS CODE AGAIN...
...
}
}
}
答案 0 :(得分:0)
几年前我写了一个基于NIO的服务器,从处理的数据量和连接的客户端数量来看,这些服务器的吞吐量非常高。我可以根据这一点分享我的经验。
请注意,在您的特定情况下,这可能不适用于100%,因此请进行适当的调整。
如果你不在下面的代码中处理数据,你会更好吗
因此请将此更改为
if (key.isReadable()) {
...
**** WHAT CAN I WRITE HERE TO HANDLE EACH READABLE CHANNEL KEY ONCE ?
**** BECAUSE IF I OPEN NEW THREAD IT WILL NOT FINISH TO HANDLE THE KEY AND I WILL GET
**** TO THIS CODE AGAIN...
...
}
以强>
if (key.isReadable()) {
// Sudo logic
// Add the selection key to a thread pool with blocking queue.
// Now your threads in the thread pool will do the heave IO task of reading bytes
// Once the bytes are read you if they need further processing like parsing out what
// Kind of message is it. You can use another thread pool that parses the data
}
如果您遵循两种线程池方法,则有两个好处。
您可能需要根据您的情况进行一些线程池调整。
我希望它有帮助:)