gpt4 book ai didi

java - Executorservice worker 没有在单独的线程中运行

转载 作者:行者123 更新时间:2023-11-30 10:45:22 25 4
gpt4 key购买 nike

我正在使用 newFixedThreadPool 来同时处理对服务器套接字的传入请求。出于某种原因,服务于客户端的工作类没有在单独的线程中运行。当我向套接字发送多个请求时,请求会按顺序处理,而不是像它们应该的那样同时处理。如果有任何不同,我正在运行 OpenJDK 1.8.0_77。

这是我主课的摘录:

    ExecutorService executorService = Executors.newFixedThreadPool(100);
ServerSocket serverSocket = new ServerSocket(5656);

while(true) {
Socket socket = serverSocket.accept();
executorService.execute(new ConnectionHandler(socket));
}

这是我的 worker 类(Class):

    public class ConnectionHandler implements Runnable {

private Socket socket;

public ConnectionHandler(Socket socket) {
this.socket = socket;
}

public void run() {

try {
Thread.sleep(5000);
} catch (InterruptedException e1) {
e1.printStackTrace();
}

BufferedReader reader = null;
PrintWriter writer = null;
try {
reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
writer = new PrintWriter(socket.getOutputStream(), true);

while(true) {
String line = reader.readLine();
if(line == null) break;
writer.println("Echo: " + line);
}
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
try {
if(reader != null) reader.close();
if(writer != null) writer.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}

}

最佳答案

对不起,我不会电脑。

问题是我在循环中将许多消息回显到套接字,但是 echo 命令按顺序发送消息并等待每条消息完成后再发送下一条消息。

关于java - Executorservice worker 没有在单独的线程中运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37035179/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com