gpt4 book ai didi

Java Socket 占用 100% CPU

转载 作者:行者123 更新时间:2023-12-02 09:38:31 26 4
gpt4 key购买 nike

我的套接字消耗了 100% 的计算机 CPU。有 150 个客户端每 30 秒异步向服务器发送消息。有谁知道如何解决这个问题?下面是我的 ServerSocket 类

public class Servidor { 

static ExecutorService es;

public static void main(String[] args) throws Exception {

es = Executors.newFixedThreadPool(150);
ServerSocket servidor = new ServerSocket(2010);

while (true) {
Socket soquete = null;

try {
System.out.println("Aguardando cliente: ");
soquete = servidor.accept();
System.out.println("Cliente Conectado: ");
es.execute(new Conexao(soquete));

} catch (Exception e) {
e.printStackTrace();
}

}

}

}

Conexao 类(实用程序类)获取客户端发送的字符串并将其保存在数据库中。下面是我的 Conexao 类(class)

public class Conexao implements Runnable{

Socket soquete;
int contador = 0;

public Conexao(Socket soquete) {
super();
this.soquete = soquete;
}

@Override
public void run(){

BufferedReader in = null;

try{
in = new BufferedReader(new InputStreamReader(soquete.getInputStream()));

while (!in.ready()) {/*System.out.println("!in.ready()");*/}

String str =in.readLine();

System.out.println("Rodando Thread"+Thread.currentThread().getName() + " : texto: " + str);

}finally{
...

if(soquete != null){
try {
soquete.close();
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
}
}


}

最佳答案

我通过删除“while (!in.ready()) {/System.out.println("!in.ready()");/}”部分并创建来解决了这个问题try block 末尾的“Thread.sleep”

关于Java Socket 占用 100% CPU,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57297776/

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