在JavaFx中管理至少三个线程

时间:2018-12-09 15:02:40

标签: java multithreading sockets javafx runnable

我正在尝试配置服务器以管理至少3个客户端,但是当我这样做时,即使在连接第一个客户端之前,我仍然遇到内存不足错误。我该如何改善?在ThreadedEchoHandler()中,我将接受客户端的请求,并接受包含服务器必须执行的所有操作的run方法。

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");
        }
    }

1 个答案:

答案 0 :(得分:1)

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

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,但是同样,它必须在之前< / em>启动线程:

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);