加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

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

发布时间:2020-12-15 05:14:51 所属栏目:Java 来源:网络整理
导读:我正在阅读一本书“ java networking 4th edition”和第9章关于服务器套接字的同时解释多线程服务器,其中每个客户端都使用单个线程处理,它说如下: Example 9-3 deliberately does not use try-with-resources for the client sockets accepted by the serve
我正在阅读一本书“ java networking 4th edition”和第9章关于服务器套接字的同时解释多线程服务器,其中每个客户端都使用单个线程处理,它说如下:

Example 9-3 deliberately does not use try-with-resources for the client sockets accepted by the server
socket. This is because the client socket escapes from the try block into a separate thread.
If you used try-with-resources,the main thread would close the socket as soon as it got
to the end of the while loop,likely before the spawned thread had finished using it.

这是例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() +"rn");
            out.flush();
        } catch (IOException ex) {
            System.err.println(ex);
        } finally {
            try {
                connection.close();
            } catch (IOException e) {
                // ignore;
            }
        }
    }
}

}

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

解决方法

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

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

代替

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

因为当使用try-with-resources块时,它会在完成后立即关闭您在括号try(…)中放置的任何内容.但你不希望这种情况发生.连接套接字是为了保持打开状态,因为它将在启动的DaytimeThread中使用.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读