线程池异步查询数据

本文展示了如何在Java中使用CompletableFuture进行异步编程,通过ExecutorService创建线程池来处理并发任务,获取整型数集合和学生集合。在TestService类中,我们创建了两个异步任务并等待它们全部完成,然后将结果整合到AsyncEntity对象中返回。在TestController中,这些异步获取的数据被用于展示。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1 异步实体类

@Data
@Builder
public class AsyncEntity {

    //整型数集合
    private List<Integer> integerList;
    //学生集合
    private List<Student> studentList;

}

2 异步获取的代码

@Service
public class TestService {

    
private static ExecutorService executorService = new ThreadPoolExecutor(10,20,1000, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>());

public AsyncEntity getAsyncEntity() {

        //1、异步获取整型List
        CompletableFuture<List<Integer>> integerListFuture =
                CompletableFuture.supplyAsync(() -> getInegerList(), executorService);

        //2、异步获取Student的List
        CompletableFuture<List<Student>> studentListFuture =
                CompletableFuture.supplyAsync(() -> getStudentList(), executorService);


        try {
            CompletableFuture.allOf(integerListFuture, studentListFuture).get(1000, TimeUnit.MILLISECONDS);
        } catch (Exception e) {
            log.error("future get failed,error={}", e);
        }

        return AsyncEntity.builder()
               .integerList(integerListFuture.getNow(Lists.newArrayList()))
               .studentList(studentListFuture.getNow(Lists.newArrayList()))
               .build();

    }


}

3 使用

@Controller
public class TestController {
   
    @Autowire
    private TestService testService;


    @RequestMapping("/test")
    public String test() {
        
       AsyncEntity asyncEntity = testService.getAsyncEntity();
       List<Integer> integerList = asyncEntity.getIntegerList();
       List<Student> studentList = asyncEntity.getStudentList();
       return "ok";
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值