Java NIO Thread selector.select()Nullpointer

时间:2012-11-11 15:23:03

标签: java multithreading sockets nio

我正在尝试在自己的线程中实现Java NIO Server。

public class MyServer extends MyThread
{
   ServerSocketChannel server;
   Selector selector;

   public MyServer
   {
      super();
      this.server = ServerSocketChannel.open();
      this.server.configureBlocking(false);
      this.server.socket().bind(new java.net.InetSocketAddress(InetAddress.getLocalHost(), 6666));
      this.selector = Selector.open();
      this.server.register(selector,SelectionKey.OP_ACCEPT);
   }
   public void run()
   {
      while(true)
      {
          this.selector.select();
          Set<SelectionKey> keys = selector.selectedKeys();
          Iterator<SelectionKey> i = keys.iterator();
          // Do channel work there
      }
   }
}

问题是我在this.selector.select()上遇到NullpointerException;在我的运行方法中。 你能帮我吗?我没有看到这个问题。

1 个答案:

答案 0 :(得分:0)

问题是我的线程的构造函数在服务器构造函数完成之前运行了线程。

因此选择器上的Nullpointer。