java socket线程池实现
时间: 2023-06-28 14:11:59 浏览: 94
在 Java 中,使用线程池可以有效地管理和复用线程,从而提高程序性能。下面是一个使用线程池实现 Socket 服务器的示例代码:
```java
import java.net.*;
import java.io.*;
import java.util.concurrent.*;
public class SocketServer {
private static final int PORT = 8888;
private static final int MAX_THREADS = 10;
public static void main(String[] args) throws Exception {
ServerSocket server = new ServerSocket(PORT);
ExecutorService pool = Executors.newFixedThreadPool(MAX_THREADS);
System.out.println("Server started.");
while (true) {
Socket client = server.accept();
System.out.println("Client connected: " + client.getInetAddress().getHostAddress());
pool.execute(new ClientHandler(client));
}
}
}
class ClientHandler implements Runnable {
private Socket client;
public ClientHandler(Socket client) {
this.client = client;
}
public void run() {
try {
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
PrintWriter out = new PrintWriter(client.getOutputStream(), true);
String line;
while ((line = in.readLine()) != null) {
System.out.println("Received from client: " + line);
out.println("Server received: " + line);
}
System.out.println("Client disconnected: " + client.getInetAddress().getHostAddress());
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
client.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
```
这个示例代码中,我们创建了一个固定大小的线程池,用来处理客户端连接。每当有一个客户端连接时,就会创建一个新的 `ClientHandler` 线程来处理客户端请求。
`ClientHandler` 类实现了 `Runnable` 接口,它的 `run()` 方法中处理了客户端请求和响应。在 `main()` 方法中,我们使用 `ExecutorService` 的 `execute()` 方法将 `ClientHandler` 对象提交到线程池中。
这样,我们就可以使用线程池来管理和复用线程,提高服务器的性能。
阅读全文