java - Java中线程完成时关闭资源

标签 java multithreading sockets

我有一个使用网络端口进行通信的线程。我添加了 cancel() 方法停止执行并关闭网络资源( How to properly stop the Thread in Java? )

private class ServerThread extends Thread {
        int portNumber;
        String serverAddress = null;

        public ServerThread(String serverAddress, int portNumber) {
            super();
            this.serverAddress = "localhost";
            this.portNumber = portNumber;
        }

        @Override
        public void run() {
            ServerSocket listener;
            Socket socket;
            try {
                listener = new ServerSocket(this.portNumber);
                socket = listener.accept();
                BufferedReader in = new BufferedReader(new InputStreamReader(
                        socket.getInputStream()));
                PrintWriter out = new PrintWriter(socket.getOutputStream(),
                        true);

                while (!isInterrupted()) {
                    String input = in.readLine();
                    if (input != null) {
                        out.println(input);
                        System.out.println("Hi:" + input);
                    }
                } // end of while loop
                System.out.println("OUT"); <-- ???
                socket.close(); <-- ???
                listener.close(); <-- ???
            } catch (IOException e) {
                e.printStackTrace();
            } 
        }

        public void cancel() {
            System.out.println("cancel called");
            interrupt();
        }
    }

问题是,当我执行 ServerThread 并发送 cancel() 消息来完成执行时,似乎这三行代码从未执行过: System.out.println("OUT");套接字.close();监听器.close();

似乎我不需要发送 cancel() 消息来完成线程。

ServerThread s = new ServerThread(serverAddress, serverPortNumber);
s.start();
...
s.cancel(); // ???

关闭线程使用的资源的推荐方法是什么? 当不再使用线程时我是否必须关闭资源?或者一切都只是自动处理?

添加

当这段代码正常工作时,线程似乎被自动终止了。

            while(true) {
                String input = in.readLine();

                if (input != null) {
                    System.out.println("Received:" + input);
                    out.println(input);
                }
            } // end of while loop
            /* System.out.println("OUT");
            socket.close();
            listener.close(); */

最佳答案

Thread#interrupt() 不会中断套接字上的阻塞 I/O 调用。尝试设置一个“停止”标志并在 cancel() 方法中关闭套接字,然后处理异常并在 while 循环中检查该标志。

InterruptibleChannel s 对中断调用使用react,但不对“老式”套接字流使用react。

关于java - Java中线程完成时关闭资源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19390629/

相关文章:

java - LibGDX : How to retrieve a picture that was taken through the camera and saved locally?

java - 使用 Java jna 和 FFTW3 包装器获取 malloc 错误

编写一个基本的多线程程序

java - Logger.getLogger ("Classname".class.getName()).log(Level.SEVERE, null, ex);

python - TypeError : can't concat bytes to str, 尝试使用 python3

Java Swing : JPanels painting over each other

java - 在 new 关键字后省略通用参数

python - 在 Python 中打印守护线程异常

javascript - Heroku Node.js + Socket.io : After deploying to Heroku, 我收到 ERR_CONNECTION_REFUSED

c++ - 使用 Boost Asio 同步 HTTPS POST