有非阻塞服务器,现在看起来像:
ServerSocketChannel server = ServerSocketChannel.open();
// ... Many stuff like initialise selector, load world, etc
while(server.isOpen())
{
selector.select();
Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
while(iterator.hasNext())
{
SelectionKey key = iterator.next();
switch(key.interestOps())
{
case SelectionKey.OP_ACCEPT:
// .... Accepting, register selector, packet handler etc
break;
case SelectionKey.OP_READ:
// .... Read-write stuff
break;
}
iterator.remove();
}
}
我需要例如 1 个线程处理 100 个连接。其他 100 个连接处理另一个线程。我试着用这段代码做到这一点:
public class ConnectionsHandler implements Runnable
{
private Selector selector;// For each thread gets its own selector
@Override public void run()
{
while(Server.server.isOpen())
{
selector.select();
Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
while(iterator.hasNext())
{
SelectionKey key = iterator.next();
// .... Read-write stuff
iterator.remove()
}
}
}
}
但是第一次接受连接后的两个线程都冻结了......没有抛出任何异常,它只是冻结了。