【发布时间】:2013-02-27 20:57:57
【问题描述】:
我已经实现了一个套接字侦听器来读取从 GPS 发送的数据,但它占用了我 90% 的 CPU。我知道这是我的代码造成的,但我看不到在哪里。
这是我的主要课程:
public class PortToDB {
ServerSocket serverSocket = null;
public void listenSocket(){
try{
serverSocket = new ServerSocket(50000);
} catch (IOException e) {
System.out.println("Could not listen on port 50000. " + e);
System.exit(-1);
}
while(true){
GPSData gd;
try{
gd = new GPSData(serverSocket.accept());
Thread t = new Thread(gd);
t.start();
} catch (IOException e) {
System.out.println("Accept failed: 50000. " + e);
System.exit(-1);
}
}
}
public static void main(String[] args) {
PortToDB portToDb = new PortToDB();
portToDb.listenSocket();
}
}
这是我的 Runnable 类:
class GPSData implements Runnable {
private Socket client;
DBHandler dbhandler = new DBHandler();
GPSData(Socket client) { this.client = client; }
public void run(){
String line;
BufferedReader in = null;
try{
in = new BufferedReader(new InputStreamReader(client.getInputStream()));
} catch (IOException e) {
System.out.println("in or out failed");
System.exit(-1);
}
while(true){
try{
if((line = in.readLine()) != null){
dbhandler.dbInsert(line);
}
} catch (IOException e) {
System.out.println("Read failed");
System.exit(-1);
}
}
}
}
【问题讨论】:
-
Code Review 或许能帮上忙/找个更好的地方问。
-
总共创建了多少线程,多久创建一次,同时有多少线程在运行?高 CPU 使用率会在使用一段时间后立即开始吗?
标签: java multithreading sockets listener port