写一个 socket发送信息的添加线程队列
时间: 2024-11-15 17:28:21 浏览: 0
在Java中创建一个Socket发送信息并使用线程队列的示例,我们可以创建一个发送任务类(如`SocketSendTask`),用于封装发送消息的操作,并将它们添加到一个线程池(例如`ExecutorService`)中执行。首先,确保已经导入了必要的包:
```java
import java.io.IOException;
import java.io.OutputStream;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
public class SocketSender {
private final ExecutorService executor;
private final LinkedBlockingQueue<SocketSendTask> queue;
public SocketSender(int threadPoolSize) {
this.executor = Executors.newFixedThreadPool(threadPoolSize);
this.queue = new LinkedBlockingQueue<>();
}
// 发送消息的任务类
static class SocketSendTask implements Runnable {
private final String message;
private final OutputStream outputStream;
public SocketSendTask(String message, OutputStream outputStream) {
this.message = message;
this.outputStream = outputStream;
}
@Override
public void run() {
try {
outputStream.write(message.getBytes());
outputStream.flush();
} catch (IOException e) {
// 处理IO异常
e.printStackTrace();
}
}
}
public void sendMessageToSocket(String message, OutputStream outputStream) {
if (!outputStream.isClosed()) {
SocketSendTask task = new SocketSendTask(message, outputStream);
queue.offer(task);
executor.execute(task);
} else {
System.out.println("Socket is closed, cannot send message.");
}
}
public void shutdown() {
executor.shutdown(); // 关闭线程池
}
}
```
在这个例子中,你可以像这样使用它:
```java
SocketSender sender = new SocketSender(5); // 创建一个包含5个线程的线程池
// 假设你已经有了socket连接
OutputStream outputStream = ...; // 获取Socket的输出流
sender.sendMessageToSocket("Hello, Server!", outputStream);
// 等待所有任务完成
sender.shutdown();
阅读全文