Java中有一千条数据怎么使用多线程发送
时间: 2024-03-16 15:42:31 浏览: 24
在Java中,可以使用`ExecutorService`和`Callable`来实现多线程发送。首先,我们需要定义一个发送函数,接收一条数据并发送。然后,创建多个`Callable`对象,每个对象都调用发送函数,并传入不同的数据。最后,将这些`Callable`对象提交给`ExecutorService`来执行。以下是一个简单的示例代码:
```java
import java.util.List;
import java.util.concurrent.*;
public class MultiThreadSend {
// 发送函数
private void send(String data) {
// 发送数据的代码
}
public void sendMessages(List<String> dataList) throws InterruptedException, ExecutionException {
// 创建线程池
ExecutorService executor = Executors.newFixedThreadPool(10);
// 创建Callable对象列表
List<Callable<Void>> callableList = new LinkedList<>();
for (String data : dataList) {
Callable<Void> callable = new Callable<Void>() {
@Override
public Void call() throws Exception {
send(data);
return null;
}
};
callableList.add(callable);
}
// 提交Callable对象列表并等待执行完成
List<Future<Void>> futures = executor.invokeAll(callableList);
for (Future<Void> future : futures) {
future.get();
}
// 关闭线程池
executor.shutdown();
}
}
```
在上面的代码中,我们首先定义了一个发送函数`send`,接收一条数据并发送。然后,创建多个`Callable`对象,每个对象都调用发送函数,并传入不同的数据。最后,将这些`Callable`对象提交给`ExecutorService`来执行,并等待它们完成。这样就可以实现多线程发送数据了。