Java SocketChannel在其他线程上关闭

Java SocketChannel在其他线程上关闭,java,multithreading,socketchannel,Java,Multithreading,Socketchannel,我有一个线程,巫婆正在测试一个socketchannel选择器。 如果socketchannel已连接且可以读取,则应启动一个消息处理程序线程,在该线程中读取和处理消息。 我需要启动处理程序线程,因为有很多事情要做,需要时间来完成它们 主线程: while (true) { try { // Wait for an event one of the registered channels this.selector.sele

我有一个线程,巫婆正在测试一个socketchannel选择器。 如果socketchannel已连接且可以读取,则应启动一个消息处理程序线程,在该线程中读取和处理消息。 我需要启动处理程序线程,因为有很多事情要做,需要时间来完成它们

主线程:

    while (true) {
        try {
            // Wait for an event one of the registered channels
            this.selector.select();

            // Iterate over the set of keys for which events are available
            Iterator selectedKeys = this.selector.selectedKeys().iterator();
            while (selectedKeys.hasNext()) {
                SelectionKey key = (SelectionKey) selectedKeys.next();
                selectedKeys.remove();

                if (!key.isValid()) {
                    continue;
                }

                // Check what event is available and deal with it
                if (key.isAcceptable()) {
                    this.accept(key);
                }
                if (key.isReadable()) {
                    this.read(key);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            Thread.sleep(200);
        } catch (InterruptedException ex) {
            ex.printStackTrace();
        }
    }
读取功能:

    private void read(SelectionKey key) throws IOException {
        // For an accept to be pending the channel must be a server socket channel.
        SocketChannel clientSocketChanel = (SocketChannel) key.channel();
        WebCommandHandler commands = new WebCommandHandler(clientSocketChanel);
        if (clientSocketChanel.isConnected()) {
            Thread cThread = new Thread(commands);
            cThread.setName("Message handler");
            cThread.start();
        }
    }
问题是,当执行处理程序线程时,给定的socketchannel已经关闭。 如果我不运行线程,只调用run()方法,那么套接字就不会关闭,因此我认为主线程迭代正在关闭给定的SocketChannel。有人能帮我找出一个解决方法吗?我如何保持SocketChannel打开,直到处理程序线程停止工作

编辑


在启动新线程之前,我可能应该从选择器中“注销”SocketChannel。。。如何从服务器注销socketChannel?

好的,我找到了解决方案。。。 因此,我们应该从选择器中注销SocketChannel。。。这可以通过调用key.cancel()函数来实现