java多线程分页查询
时间: 2023-11-23 13:57:24 浏览: 211
以下是Java多线程分页查询的示例代码:
```java
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;
public class MultiThreadedPagination {
public static void main(String[] args) throws InterruptedException, ExecutionException {
// 创建一个线程池
ExecutorService executor = Executors.newFixedThreadPool(5);
// 模拟数据库中的数据
List<Integer> data = new ArrayList<>();
for (int i = 1; i <= 100; i++) {
data.add(i);
}
// 分页查询
int pageSize = 10;
int totalPage = (int) Math.ceil((double) data.size() / pageSize);
List<Future<List<Integer>>> futures = new ArrayList<>();
for (int i = 0; i < totalPage; i++) {
int fromIndex = i * pageSize;
int toIndex = Math.min(fromIndex + pageSize, data.size());
List<Integer> subList = data.subList(fromIndex, toIndex);
Callable<List<Integer>> task = new PaginationTask(subList);
Future<List<Integer>> future = executor.submit(task);
futures.add(future);
}
// 输出查询结果
for (Future<List<Integer>> future : futures) {
List<Integer> result = future.get();
System.out.println(result);
}
// 关闭线程池
executor.shutdown();
}
static class PaginationTask implements Callable<List<Integer>> {
private List<Integer> data;
public PaginationTask(List<Integer> data) {
this.data = data;
}
@Override
public List<Integer> call() throws Exception {
// 模拟查询数据库
Thread.sleep(1000);
return data;
}
}
}
```
上述代码中,我们首先创建了一个线程池,然后模拟了一个包含100个整数的数据集合。接着,我们将数据集合按照每页10个的方式进行分页查询,每页的查询任务都由一个Callable对象表示。我们将所有的查询任务提交给线程池,并使用Future对象来保存每个查询任务的结果。最后,我们遍历所有的Future对象,获取查询结果并输出。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)