异步线程简单例子

    @Autowired
    private ThreadPoolTaskExecutor taskExecutor;

public List<Map> asyncGetTaskCount(String type, String userId) {
        List<Map> list = new ArrayList<>();
        final CountDownLatch latch =new CountDownLatch(3);
        try{
            List<Integer> status = Arrays.asList(2, 3, 4);
            List<Future<Map>> futureList = new ArrayList<>();

            status.forEach(item -> {
                taskExecutor.submit(() ->{
                    try {
                        log.info("thread1->doWork");
                        CompletableFuture<Map> future = processService.aysncTaskCount(type, item, userId);
                        futureList.add(future);
                    } finally {
                        log.info("thread1->end");
                        //线程数-1
                        latch.countDown();
                    }
                });
            });
            latch.await(10, TimeUnit.MINUTES);
            for(Future<Map> result : futureList){
                Map map = result.get();
                list.add(map);
            }

        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        return list;
    }

---------------------------------------------------------------
   @Async("taskCountExecutor")
    @Override
    public CompletableFuture<Map> aysncTaskCount(String type, Integer dataStatus, String userId) {
        Map map = taskCount(type, dataStatus, userId);
        return CompletableFuture.completedFuture(map);
    }
上一篇:外观模式


下一篇:我看看是什么