在 JavaFx 中管理至少三个线程

Manage at least three thread in JavaFx

我正在尝试将我的服务器配置为管理至少 3 个客户端,但是当我这样做时,甚至在连接第一个客户端之前就出现了内存不足错误。我该如何改进它?在 ThreadedEchoHandler() 中,我接受客户端请求的部分和包含服务器必须执行的所有操作的 运行 方法。

public void initModel() throws IOException {
    contenutoTextArea.append("Waiting for connections\n");
    textarea.setText(contenutoTextArea.toString());
    s = new ServerSocket(5000);
    while (true) {
        Runnable r = new ThreadedEchoHandler();
        new Thread(r).start();
    }
}

编辑:ThreadedEchoHandler 的开始:

lass ThreadedEchoHandler implements Runnable {

    private Socket incoming;

    private String nomeAccount = "";

    public void run() {
        try {
            incoming = s.accept();
        } catch (IOException ex) {
            System.out.println("Unable to accept requests");
        }
    }

您应该在发生 while 循环的同一个线程中执行 accept,然后在获得新的已接受连接后,启动一个新线程:

while (true) {
    Socket incoming = s.accept();
    Runnable r = new ThreadedEchoHandler(incoming);
    new Thread(r).start();
}

并修改 ThreadEchoHandler 以从外部获取其 Socket

class ThreadedEchoHandler implements Runnable {
    final private Socket incoming;
    private String nomeAccount = "";

    ThreadedEchoHandler(Socket incoming) {
        this.incoming = incoming;
    }

    public void run() {
        // do stuff
    }
}

当然你可以用各种方式组织它,比如 ThreadedEchoHandler 可以从构造函数启动它的线程,甚至也可以做 accept,但是同样,它必须发生 开始线程之前:

class ThreadedEchoHandler implements Runnable {
    final private Socket incoming;
    private String nomeAccount = "";

    ThreadedEchoHandler(ServerSocket serv) throws IOException {
        incoming = serv.accept();
        new Thread(this).start();
    }

    public void run() {
        // do stuff
    }
}

那么循环可能是这样的:

while (true) new ThreadedEchoHandler(s);