在java中使用多线程服务器中的资源尝试

Dan*_*vic 3 java sockets multithreading

我正在阅读一本书"java networking 4th edition"和第9章关于服务器套接字,同时解释多线程服务器,其中每个客户端使用单个线程处理,它说如下:

例9-3故意不对服务器套接字接受的客户端套接字使用try-with-resources.这是因为客户端套接字从try块转义为单独的线程.如果您使用了try-with-resources,主线程会在它到达while循环结束时关闭套接字,可能在生成的线程完成使用之前.

这是例9-3

import java.net.*;
import java.io.*;
import java.util.Date;
public class MultithreadedDaytimeServer {
public final static int PORT = 13;
public static void main(String[] args) {
    try (ServerSocket server = new ServerSocket(PORT)) {
        while (true) {
            try {
                Socket connection = server.accept();
                Thread task = new DaytimeThread(connection);
                task.start();
            } catch (IOException ex) {}
        }
    } catch (IOException ex) {
        System.err.println("Couldn't start server");
    }
}
private static class DaytimeThread extends Thread {
    private Socket connection;
    DaytimeThread(Socket connection) {
        this.connection = connection;
    }
    @Override
    public void run() {
        try {
            Writer out = new OutputStreamWriter(connection.getOutputStream());
            Date now = new Date();
            out.write(now.toString() +"\r\n");
            out.flush();
        } catch (IOException ex) {
            System.err.println(ex);
        } finally {
            try {
                connection.close();
            } catch (IOException e) {
                // ignore;
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

}

我真的不明白为什么会发生这种情况,为什么主线程要从另一个线程关闭套接字,是因为套接字对象是在主线程中创建的,引用是在线程构造函数中提供的?

Leo*_*Aso 9

这本书的意思是他们选择这样做

try {
    Socket connection = server.accept();
    Thread task = new DaytimeThread(connection);
    task.start();
} catch (IOException ex) {}
Run Code Online (Sandbox Code Playgroud)

代替

try(Socket connection = server.accept()) {
    Thread task = new DaytimeThread(connection);
    task.start();
} catch (IOException ex) {}
Run Code Online (Sandbox Code Playgroud)

因为当使用try-with-resources块时,它会在完成后立即关闭放在括号中的任何内容try(...).但你不希望这种情况发生.该connection插座的意思,因为它会在被用来保持开放DaytimeThread而启动.