在java中使用多线程服务器中的资源尝试
我正在阅读一本书“
java networking 4th edition”和第9章关于服务器套接字的同时解释多线程服务器,其中每个客户端都使用单个线程处理,它说如下:
这是例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中使用. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |