Java常用代码合集

12/15/2023 异步多线程

# 循环体使用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();
            }
        }
    }     
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31