Java常用代码合集

lijunyi2023-12-15java异步多线程

循环体使用CompletableFuture实践

public void inspectionPurchaseRequisitionByBxId(Integer bxId){
List<Integer> idList = AutoInspectionPurchaseOrderHandle.getIds();
    if (CollectionUtil.isNotEmpty(idList))
    {
        // 获取线程池
        ThreadPoolTaskExecutor commonTaskSchedulingThreadPool = SpringUtil.getBean("commonTaskSchedulingThreadPool");
         List<CompletableFuture<Integer>> futures = new ArrayList<>();
        for (Integer id : idList)
        {
            futures.add(
                    CompletableFuture.supplyAsync(() -> {
                        log.info("线程{}执行方法",Thread.currentThread().getName());
                        // 业务代码
                        return id;
                    }, commonTaskSchedulingThreadPool)
            );
        }
        // 所有子线程都需要完成后再执行主线程
        CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).join();
        for (CompletableFuture<Integer> future : futures)
        {
            try {
                Integer s = future.get();
                log.info("返回值" + s);
            }catch (InterruptedException | ExecutionException e)
            {
                e.printStackTrace();
            }
        }
    }     
}
Last Updated 5/24/2024, 8:21:58 AM
公告
这里是新博客,陆续升级中...

Navicat 17有关激活请查看GitLab
docker镜像加速已完成,欢迎大家使用.

博客有AI啦,发现了嘛...