• 【日常业务开发】Java实现异步编程


    Java实现异步编程

    异步执行对于开发者来说并不陌生,在实际的开发过程中,很多场景多会使用到异步,相比同步执行,异步可以大大缩短请求链路耗时时间,比如:发送短信、邮件、异步更新等,这些都是典型的可以通过异步实现的场景。

    什么是异步

    首先我们先看一个常见的用户下单的场景:
    在这里插入图片描述

    同步操作中,我们执行到 发送短信 的时候,我们必须等待这个方法彻底执行完才能执行 赠送积分 这个操作,如果 赠送积分 这个动作执行时间较长,发送短信需要等待,这就是典型的同步场景。

    实际上,发送短信和赠送积分没有任何的依赖关系,通过异步,我们可以实现赠送积分发送短信这两个操作能够同时进行,比如:

    在这里插入图片描述

    异步的八种实现方式

    1. 线程Thread
    2. Future
    3. 异步框架CompletableFuture
    4. Spring注解@Async
    5. Spring ApplicationEvent事件
    6. 消息队列
    7. 第三方异步框架,比如Hutool的ThreadUtil
    8. Guava异步

    异步编程

    线程异步

    public class AsyncThread extends Thread {
    
        @Override
        public void run() {
            System.out.println("Current thread name:" + Thread.currentThread().getName() + " Send email success!");
        }
    
        public static void main(String[] args) {
            AsyncThread asyncThread = new AsyncThread();
            asyncThread.run();
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    当然如果每次都创建一个Thread线程,频繁的创建、销毁,浪费系统资源,我们可以采用线程池:

    private ExecutorService executorService = Executors.newCachedThreadPool();
    
    public void fun() {
        executorService.submit(new Runnable() {
            @Override
            public void run() {
                log.info("执行业务逻辑...");
            }
        });
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    可以将业务逻辑封装到RunnableCallable中,交由线程池来执行。

    Future异步

    @Slf4j
    public class FutureManager {
    
        public String execute() throws Exception {
    
            ExecutorService executor = Executors.newFixedThreadPool(1);
            Future<String> future = executor.submit(new Callable<String>() {
                @Override
                public String call() throws Exception {
    
                    System.out.println(" --- task start --- ");
                    Thread.sleep(3000);
                    System.out.println(" --- task finish ---");
                    return "this is future execute final result!!!";
                }
            });
    
            //这里需要返回值时会阻塞主线程
            String result = future.get();
            log.info("Future get result: {}", result);
            return result;
        }
    
        @SneakyThrows
        public static void main(String[] args) {
            FutureManager manager = new FutureManager();
            manager.execute();
        }
    }
    
    • 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

    Future的不足之处的包括以下几点:

    1. 无法被动接收异步任务的计算结果:虽然我们可以主动将异步任务提交给线程池中的线程来执行,但是待异步任务执行结束之后,主线程无法得到任务完成与否的通知,它需要通过get方法主动获取任务执行的结果。
    2. Future件彼此孤立:有时某一个耗时很长的异步任务执行结束之后,你想利用它返回的结果再做进一步的运算,该运算也会是一个异步任务,两者之间的关系需要程序开发人员手动进行绑定赋予,Future并不能将其形成一个任务流(pipeline),每一个Future都是彼此之间都是孤立的,所以才有了后面的CompletableFuture,CompletableFuture就可以将多个Future串联起来形成任务流。
    3. Futrue没有很好的错误处理机制:截止目前,如果某个异步任务在执行发的过程中发生了异常,调用者无法被动感知,必须通过捕获get方法的异常才知晓异步任务执行是否出现了错误,从而在做进一步的判断处理。

    CompletableFuture实现异步

    public class CompletableFutureCompose {
    
        /**
         * thenAccept子任务和父任务公用同一个线程
         */
        @SneakyThrows
        public static void thenRunAsync() {
            CompletableFuture<Integer> cf1 = CompletableFuture.supplyAsync(() -> {
                System.out.println(Thread.currentThread() + " cf1 do something....");
                return 1;
            });
            CompletableFuture<Void> cf2 = cf1.thenRunAsync(() -> {
                System.out.println(Thread.currentThread() + " cf2 do something...");
            });
            //等待任务1执行完成
            System.out.println("cf1结果->" + cf1.get());
            //等待任务2执行完成
            System.out.println("cf2结果->" + cf2.get());
        }
    
        public static void main(String[] args) {
            thenRunAsync();
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24

    我们不需要显式使用ExecutorService,CompletableFuture 内部使用了ForkJoinPool来处理异步任务,如果在某些业务场景我们想自定义自己的异步线程池也是可以的。

    Spring的@Async异步

    自定义异步线程池

    /**
     * 线程池参数配置,多个线程池实现线程池隔离,@Async注解,默认使用系统自定义线程池,可在项目中设置多个线程池,在异步调用的时候,指明需要调用的线程池名称,比如:@Async("taskName")
     *
     **/
    @EnableAsync
    @Configuration
    public class TaskPoolConfig {
    
        /**
         * 自定义线程池
         *
         * @author: jacklin
         * @since: 2021/11/16 17:41
         **/
        @Bean("taskExecutor")
        public Executor taskExecutor() {
            //返回可用处理器的Java虚拟机的数量 12
            int i = Runtime.getRuntime().availableProcessors();
            System.out.println("系统最大线程数  : " + i);
            ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
            //核心线程池大小
            executor.setCorePoolSize(16);
            //最大线程数
            executor.setMaxPoolSize(20);
            //配置队列容量,默认值为Integer.MAX_VALUE
            executor.setQueueCapacity(99999);
            //活跃时间
            executor.setKeepAliveSeconds(60);
            //线程名字前缀
            executor.setThreadNamePrefix("asyncServiceExecutor -");
            //设置此执行程序应该在关闭时阻止的最大秒数,以便在容器的其余部分继续关闭之前等待剩余的任务完成他们的执行
            executor.setAwaitTerminationSeconds(60);
            //等待所有的任务结束后再关闭线程池
            executor.setWaitForTasksToCompleteOnShutdown(true);
            return executor;
        }
    }
    
    • 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
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    public interface AsyncService {
    
        MessageResult sendSms(String callPrefix, String mobile, String actionType, String content);
    
        MessageResult sendEmail(String email, String subject, String content);
    }
    
    @Slf4j
    @Service
    public class AsyncServiceImpl implements AsyncService {
    
        @Autowired
        private IMessageHandler mesageHandler;
    
        @Override
        @Async("taskExecutor")
        public MessageResult sendSms(String callPrefix, String mobile, String actionType, String content) {
            try {
    
                Thread.sleep(1000);
                mesageHandler.sendSms(callPrefix, mobile, actionType, content);
    
            } catch (Exception e) {
                log.error("发送短信异常 -> ", e)
            }
        }
        
        
        @Override
        @Async("taskExecutor")
        public sendEmail(String email, String subject, String content) {
            try {
    
                Thread.sleep(1000);
                mesageHandler.sendsendEmail(email, subject, content);
    
            } catch (Exception e) {
                log.error("发送email异常 -> ", e)
            }
        }
    }
    
    • 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
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41

    在实际项目中, 使用@Async调用线程池,推荐等方式是是使用自定义线程池的模式,不推荐直接使用@Async直接实现异步。

    Spring ApplicationEvent事件实现异步

    定义事件

    public class AsyncSendEmailEvent extends ApplicationEvent {
    
        /**
         * 邮箱
         **/
        private String email;
    
       /**
         * 主题
         **/
        private String subject;
    
        /**
         * 内容
         **/
        private String content;
      
        /**
         * 接收者
         **/
        private String targetUserId;
    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23

    定义事件处理器

    @Slf4j
    @Component
    public class AsyncSendEmailEventHandler implements ApplicationListener<AsyncSendEmailEvent> {
    
        @Autowired
        private IMessageHandler mesageHandler;
        
        @Async("taskExecutor")
        @Override
        public void onApplicationEvent(AsyncSendEmailEvent event) {
            if (event == null) {
                return;
            }
    
            String email = event.getEmail();
            String subject = event.getSubject();
            String content = event.getContent();
            String targetUserId = event.getTargetUserId();
            mesageHandler.sendsendEmailSms(email, subject, content, targerUserId);
          }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21

    另外,可能有些时候采用ApplicationEvent实现异步的使用,当程序出现异常错误的时候,需要考虑补偿机制,那么这时候可以结合Spring Retry重试来帮助我们避免这种异常造成数据不一致问题。

    消息队列

    生产者

    @Slf4j
    @SpringBootTest
    public class ProducerRocketMqBootApiTest {
        
        @Autowired
        private RocketMQTemplate rocketMQTemplate;
         /**
         * 发送的是同步消息
         * rocketMQTemplate.syncSend()
         * rocketMQTemplate.send()
         * rocketMQTemplate.convertAndSend()
         * 这三种发送消息的方法,底层都是调用syncSend
         */
        
        /**
         * 测试发送简单的消息
         *
         * @throws Exception
         */
        @Test
        public void testSimpleMsg() {
            SendResult sendResult = rocketMQTemplate.syncSend(MqConstant.TOPIC_TAG, "我是一个同步简单消息");
            System.out.println(sendResult.getSendStatus());
            System.out.println(sendResult.getMsgId());
            System.out.println(sendResult.getMessageQueue());
        }
    }
    
    • 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

    消费者

    @Slf4j
    @Component
    @RocketMQMessageListener(topic = "${rocketmq.topic}", consumerGroup = "${rocketmq.consumer.group}")
    public class BaseConsumerListener implements RocketMQListener<MessageExt>, RocketMQPushConsumerLifecycleListener {
    
        @Autowired
        private MessageMapper messageMapper;
    
    //    @Autowired
    //    private BitMapBloomFilter bitMapBloomFilter;
    
        @Autowired
        private ApplicationContext applicationContext;
    
        @Override
        public void onMessage(MessageExt message) {
            String topic = message.getTopic();
            String tag = message.getTags();
            byte[] body = message.getBody();
            String keys = message.getKeys();
            String msgId = message.getMsgId();
            String realTopic = message.getProperty("REAL_TOPIC");
            String originMessageId = message.getProperty("ORIGIN_MESSAGE_ID");
    
            // 获取重试的次数 失败一次消息中的失败次数会累加一次
            int reconsumeTimes = message.getReconsumeTimes();
    
            String jsonBody = JackJsonUtil.toJSONString((new String(body)));
            log.info("消息监听类: msgId:{},topic:{}, tag:{}, body:{},keys:{},realTopic:{},originMessageId:{},reconsumeTimes:{}", msgId, topic, tag, jsonBody, keys, realTopic, originMessageId, reconsumeTimes);
    
            // 布隆过滤器进行去重
    //        if (bitMapBloomFilter.contains(keys)) {
    //            return;
    //        }
    //        bitMapBloomFilter.add(keys);
    
            // 消费者幂等处理: 设计去重表,防止重复消费
            messageMapper.insert(buildMessage(message));
            applicationContext.publishEvent(new BaseEvent(tag, jsonBody));
        }
    
        private Message buildMessage(MessageExt messageExt) {
            Message message = new Message();
            message.setMsgId(messageExt.getMsgId());
            message.setMsgTopic(messageExt.getTopic());
            message.setMsgTag(messageExt.getTags());
    
            message.setMsgBody(JackJsonUtil.toJSONString((new String(messageExt.getBody()))));
    
    
            // 判断是否是重试消息
            String realTopic = messageExt.getProperty("REAL_TOPIC");
            String originMessageId = messageExt.getProperty("ORIGIN_MESSAGE_ID");
            if (StrUtil.isNotBlank(realTopic) && StrUtil.isNotBlank(originMessageId) ) {
                message.setMsgType("2");
                message.setMsgKeys(messageExt.getKeys()+":"+originMessageId+":"+IdUtil.fastUUID());
            } else {
                message.setMsgType("1");
                message.setMsgKeys(messageExt.getKeys());
            }
            message.setMsgRetryId(originMessageId);
            message.setMsgRetryTopic(realTopic);
            message.setCreateTime(new Date());
            return message;
        }
    
    
        @Override
        public void prepareStart(DefaultMQPushConsumer consumer) {
            // 设置最大重试次数
            consumer.setMaxReconsumeTimes(3);
            // 如下,设置其它consumer相关属性
            consumer.setPullBatchSize(16);
        }
    }
    
    
    • 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
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76

    ThreadUtil异步工具类

    @Slf4j
    public class ThreadUtils {
    
        public static void main(String[] args) {
            for (int i = 0; i < 3; i++) {
                ThreadUtil.execAsync(() -> {
                    ThreadLocalRandom threadLocalRandom = ThreadLocalRandom.current();
                    int number = threadLocalRandom.nextInt(20) + 1;
                    System.out.println(number);
                });
                log.info("当前第:" + i + "个线程");
            }
    
            log.info("task finish!");
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

    Guava异步

    GuavaListenableFuture顾名思义就是可以监听的Future,是对java原生Future的扩展增强。我们知道Future表示一个异步计算任务,当任务完成时可以得到计算结果。如果我们希望一旦计算完成就拿到结果展示给用户或者做另外的计算,就必须使用另一个线程不断的查询计算状态。这样做,代码复杂,而且效率低下。使用Guava ListenableFuture可以帮我们检测Future是否完成了,不需要再通过get()方法苦苦等待异步的计算结果,如果完成就自动调用回调函数,这样可以减少并发程序的复杂度。

    ListenableFuture是一个接口,它从jdkFuture接口继承,添加了void addListener(Runnable listener, Executor executor)方法。

    我们看下如何使用ListenableFuture。首先需要定义ListenableFuture的实例:

     ListeningExecutorService executorService = MoreExecutors.listeningDecorator(Executors.newCachedThreadPool());
            final ListenableFuture<Integer> listenableFuture = executorService.submit(new Callable<Integer>() {
                @Override
                public Integer call() throws Exception {
                    log.info("callable execute...")
                    TimeUnit.SECONDS.sleep(1);
                    return 1;
                }
            });
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    首先通过MoreExecutors类的静态方法listeningDecorator方法初始化一个ListeningExecutorService的方法,然后使用此实例的submit方法即可初始化ListenableFuture对象。

    ListenableFuture要做的工作,在Callable接口的实现类中定义,这里只是休眠了1秒钟然后返回一个数字1,有了ListenableFuture实例,可以执行此Future并执行Future完成之后的回调函数。

     Futures.addCallback(listenableFuture, new FutureCallback<Integer>() {
        @Override
        public void onSuccess(Integer result) {
            //成功执行...
            System.out.println("Get listenable future's result with callback " + result);
        }
    
        @Override
        public void onFailure(Throwable t) {
            //异常情况处理...
            t.printStackTrace();
        }
    });
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    CompletableFuture异步编排工具类

    在Java8中,CompletableFuture提供了非常强大的Future的扩展功能,可以帮助我们简化异步编程的复杂性,并且提供了函数式编程的能力,可以通过回调的方式处理计算结果,也提供了转换和组合 CompletableFuture 的方法。

    它可能代表一个明确完成的Future,也有可能代表一个完成阶段( CompletionStage ),它支持在计算完成以后触发一些函数或执行某些动作。

    创建异步对象

    runAsync和 supplyAsync

    CompletableFuture 提供了四个静态方法来创建一个异步操作。

    public static CompletableFuture<Void> runAsync(Runnable runnable)
    public static CompletableFuture<Void> runAsync(Runnable runnable, Executor executor)
    public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier)
    public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier, Executor executor)
    
    • 1
    • 2
    • 3
    • 4

    没有指定Executor的方法会使用ForkJoinPool.commonPool() 作为它的线程池执行异步代码。如果指定线程池,则使用指定的线程池运行。以下所有的方法都类同。

    • runAsync方法不支持返回值。
    • supplyAsync可以支持返回值。

    计算完成时回调方法

    当CompletableFuture的计算结果完成,或者抛出异常的时候,可以执行特定的Action。主要是下面的方法:

    public CompletableFuture<T> whenComplete(BiConsumer<? super T,? super Throwable> action)
    public CompletableFuture<T> whenCompleteAsync(BiConsumer<? super T,? super Throwable> action)
    public CompletableFuture<T> whenCompleteAsync(BiConsumer<? super T,? super Throwable> action, Executor executor)
    public CompletableFuture<T> exceptionally(Function<Throwable,? extends T> fn)
    
    • 1
    • 2
    • 3
    • 4

    whenComplete 可以处理正常和异常的计算结果,exceptionally 处理异常情

    whenCompletewhenCompleteAsync 的区别:

    • whenComplete:是执行当前任务的线程执行继续执行 whenComplete 的任务。
    • whenCompleteAsync:是执行把 whenCompleteAsync 这个任务继续提交给线程池来进行执行。

    方法不以 Async 结尾,意味着 Action 使用相同的线程执行,而 Async 可能会使用其他线程执行(如果是使用相同的线程池,也可能会被同一个线程选中执行)

    public static void whenComplete() throws Exception {
        CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
            }
            if(new Random().nextInt()%2>=0) {
                int i = 12/0;
            }
            System.out.println("run end ...");
        });
    
        future.whenComplete(new BiConsumer<Void, Throwable>() {
            @Override
            public void accept(Void t, Throwable action) {
                System.out.println("执行完成!");
            }
    
        });
        future.exceptionally(new Function<Throwable, Void>() {
            @Override
            public Void apply(Throwable t) {
                System.out.println("执行失败!"+t.getMessage());
                return null;
            }
        });
    
        TimeUnit.SECONDS.sleep(2);
    }
    
    
    • 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

    handle 方法

    handle 是执行任务完成时对结果的处理。

    handle 方法和 thenApply 方法处理方式基本一样。不同的是 handle 是在任务完成后再执行,还可以处理异常的任务。thenApply 只可以执行正常的任务,任务出现异常则不执行 thenApply 方法。

    public <U> CompletionStage<U> handle(BiFunction<? super T, Throwable, ? extends U> fn);
    public <U> CompletionStage<U> handleAsync(BiFunction<? super T, Throwable, ? extends U> fn);
    public <U> CompletionStage<U> handleAsync(BiFunction<? super T, Throwable, ? extends U> fn,Executor executor);
    
    • 1
    • 2
    • 3
    public static void handle() throws Exception{
        CompletableFuture<Integer> future = CompletableFuture.supplyAsync(new Supplier<Integer>() {
    
            @Override
            public Integer get() {
                int i= 10/0;
                return new Random().nextInt(10);
            }
        }).handle(new BiFunction<Integer, Throwable, Integer>() {
            @Override
            public Integer apply(Integer param, Throwable throwable) {
                int result = -1;
                if(throwable==null){
                    result = param * 2;
                }else{
                    System.out.println(throwable.getMessage());
                }
                return result;
            }
         });
        System.out.println(future.get());
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22

    线程串行化方法

    thenApply

    当一个线程依赖另一个线程时,获取上一个任务返回的结果,并返回当前任务的返回值

    public <U> CompletableFuture<U> thenApply(Function<? super T,? extends U> fn)
    public <U> CompletableFuture<U> thenApplyAsync(Function<? super T,? extends U> fn)
    public <U> CompletableFuture<U> thenApplyAsync(Function<? super T,? extends U> fn, Executor executor)
    
    • 1
    • 2
    • 3

    Function

    • T:上一个任务返回结果的类型
    • U:当前任务的返回值类型
    private static void thenApply() throws Exception {
        CompletableFuture<Long> future = CompletableFuture.supplyAsync(new Supplier<Long>() {
            @Override
            public Long get() {
                long result = new Random().nextInt(100);
                System.out.println("result1="+result);
                return result;
            }
        }).thenApply(new Function<Long, Long>() {
            @Override
            public Long apply(Long t) {
                long result = t*5;
                System.out.println("result2="+result);
                return result;
            }
        });
        long result = future.get();
        System.out.println(result);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19

    thenAccept

    消费处理结果。接收任务的处理结果,并消费处理,无返回结果。

    public CompletionStage<Void> thenAccept(Consumer<? super T> action);
    public CompletionStage<Void> thenAcceptAsync(Consumer<? super T> action);
    public CompletionStage<Void> thenAcceptAsync(Consumer<? super T> action,Executor executor);
    
    • 1
    • 2
    • 3
    public static void thenAccept() throws Exception{
        CompletableFuture<Void> future = CompletableFuture.supplyAsync(new Supplier<Integer>() {
            @Override
            public Integer get() {
                return new Random().nextInt(10);
            }
        }).thenAccept(integer -> {
            System.out.println(integer);
        });
        future.get();
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    thenRun

    只要上面的任务执行完成,就开始执行 thenRun,只是处理完任务后,执行thenRun 的后续操作

    public static void thenRun() throws Exception{
        CompletableFuture<Void> future = CompletableFuture.supplyAsync(new Supplier<Integer>() {
            @Override
            public Integer get() {
                return new Random().nextInt(10);
            }
        }).thenRun(() -> {
            System.out.println("thenRun ...");
        });
        future.get();
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    thenCompose 方法

    thenCompose 方法允许你对两个 CompletionStage 进行流水线操作,第一个操作完成时,将其结果作为参数传递给第二个操作。

    private static void thenCompose() throws Exception {
           CompletableFuture<Integer> f = CompletableFuture.supplyAsync(new Supplier<Integer>() {
               @Override
               public Integer get() {
                   int t = new Random().nextInt(3);
                   System.out.println("t1="+t);
                   return t;
               }
           }).thenCompose(new Function<Integer, CompletionStage<Integer>>() {
               @Override
               public CompletionStage<Integer> apply(Integer param) {
                   return CompletableFuture.supplyAsync(new Supplier<Integer>() {
                       @Override
                       public Integer get() {
                           int t = param *2;
                           System.out.println("t2="+t);
                           return t;
                       }
                   });
               }
    
           });
           System.out.println("thenCompose result : "+f.get());
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24

    两任务组合 - 都要完成

    thenCombine 合并任务

    组合两个 future,获取两个 future 的返回结果,并返回当前任务的返回值

    private static void thenCombine() throws Exception {
        CompletableFuture<String> future1 = CompletableFuture.supplyAsync(new Supplier<String>() {
            @Override
            public String get() {
                return "hello";
            }
        });
        CompletableFuture<String> future2 = CompletableFuture.supplyAsync(new Supplier<String>() {
            @Override
            public String get() {
                return "hello";
            }
        });
        CompletableFuture<String> result = future1.thenCombine(future2, new BiFunction<String, String, String>() {
            @Override
            public String apply(String t, String u) {
                return t+" "+u;
            }
        });
        System.out.println(result.get());
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21

    thenAcceptBoth

    组合两个 future,获取两个 future 任务的返回结果,然后处理任务,没有返回值

    private static void thenAcceptBoth() throws Exception {
        CompletableFuture<Integer> f1 = CompletableFuture.supplyAsync(new Supplier<Integer>() {
            @Override
            public Integer get() {
                int t = new Random().nextInt(3);
                try {
                    TimeUnit.SECONDS.sleep(t);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("f1="+t);
                return t;
            }
        });
    
        CompletableFuture<Integer> f2 = CompletableFuture.supplyAsync(new Supplier<Integer>() {
            @Override
            public Integer get() {
                int t = new Random().nextInt(3);
                try {
                    TimeUnit.SECONDS.sleep(t);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("f2="+t);
                return t;
            }
        });
        f1.thenAcceptBoth(f2, new BiConsumer<Integer, Integer>() {
            @Override
            public void accept(Integer t, Integer u) {
                System.out.println("f1="+t+";f2="+u+";");
            }
        });
    }
    
    • 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
    • 32
    • 33
    • 34
    • 35

    runAfterBoth

    组合两个 future,不需要获取 future 的结果,只需两个 future 处理完任务后,处理该任务

    private static void runAfterBoth() throws Exception {
        CompletableFuture<Integer> f1 = CompletableFuture.supplyAsync(new Supplier<Integer>() {
            @Override
            public Integer get() {
                int t = new Random().nextInt(3);
                try {
                    TimeUnit.SECONDS.sleep(t);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("f1="+t);
                return t;
            }
        });
    
        CompletableFuture<Integer> f2 = CompletableFuture.supplyAsync(new Supplier<Integer>() {
            @Override
            public Integer get() {
                int t = new Random().nextInt(3);
                try {
                    TimeUnit.SECONDS.sleep(t);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("f2="+t);
                return t;
            }
        });
        f1.runAfterBoth(f2, new Runnable() {
    
            @Override
            public void run() {
                System.out.println("上面两个任务都执行完成了。");
            }
        });
    }
    
    • 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
    • 32
    • 33
    • 34
    • 35
    • 36

    两任务组合 - 一个完成

    applyToEither 方法

    两个任务有一个执行完成,获取它的返回值,处理任务并有新的返回值。

    private static void applyToEither() throws Exception {
        CompletableFuture<Integer> f1 = CompletableFuture.supplyAsync(new Supplier<Integer>() {
            @Override
            public Integer get() {
                int t = new Random().nextInt(3);
                try {
                    TimeUnit.SECONDS.sleep(t);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("f1="+t);
                return t;
            }
        });
        CompletableFuture<Integer> f2 = CompletableFuture.supplyAsync(new Supplier<Integer>() {
            @Override
            public Integer get() {
                int t = new Random().nextInt(3);
                try {
                    TimeUnit.SECONDS.sleep(t);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("f2="+t);
                return t;
            }
        });
    
        CompletableFuture<Integer> result = f1.applyToEither(f2, new Function<Integer, Integer>() {
            @Override
            public Integer apply(Integer t) {
                System.out.println(t);
                return t * 2;
            }
        });
    
        System.out.println(result.get());
    }
    
    • 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
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38

    acceptEither 方法

    两个任务有一个执行完成,获取它的返回值,处理任务,没有新的返回值。

    private static void acceptEither() throws Exception {
        CompletableFuture<Integer> f1 = CompletableFuture.supplyAsync(new Supplier<Integer>() {
            @Override
            public Integer get() {
                int t = new Random().nextInt(3);
                try {
                    TimeUnit.SECONDS.sleep(t);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("f1="+t);
                return t;
            }
        });
    
        CompletableFuture<Integer> f2 = CompletableFuture.supplyAsync(new Supplier<Integer>() {
            @Override
            public Integer get() {
                int t = new Random().nextInt(3);
                try {
                    TimeUnit.SECONDS.sleep(t);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("f2="+t);
                return t;
            }
        });
        f1.acceptEither(f2, new Consumer<Integer>() {
            @Override
            public void accept(Integer t) {
                System.out.println(t);
            }
        });
    }
    
    • 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
    • 32
    • 33
    • 34
    • 35

    runAfterEither 方法

    两个任务有一个执行完成,不需要获取 future 的结果,处理任务,也没有返回值

    private static void runAfterEither() throws Exception {
        CompletableFuture<Integer> f1 = CompletableFuture.supplyAsync(new Supplier<Integer>() {
            @Override
            public Integer get() {
                int t = new Random().nextInt(3);
                try {
                    TimeUnit.SECONDS.sleep(t);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("f1="+t);
                return t;
            }
        });
    
        CompletableFuture<Integer> f2 = CompletableFuture.supplyAsync(new Supplier<Integer>() {
            @Override
            public Integer get() {
                int t = new Random().nextInt(3);
                try {
                    TimeUnit.SECONDS.sleep(t);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("f2="+t);
                return t;
            }
        });
        f1.runAfterEither(f2, new Runnable() {
    
            @Override
            public void run() {
                System.out.println("上面有一个已经完成了。");
            }
        });
    }
    
    • 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
    • 32
    • 33
    • 34
    • 35
    • 36

    多任务组合

    public static CompletableFuture<Void> allOf(CompletableFuture<?>... cfs);
    public static CompletableFuture<Object> anyOf(CompletableFuture<?>... cfs);
    
    • 1
    • 2

    allOf:等待所有任务完成
    anyOf:只要有一个任务完成

    实际业务场景

    在这里插入图片描述

    假设要求:

    第一,要先拿到商品的基本信息 基本信息里面有 销售id 和 销售规格id

    第二,拿到商品基本信息后 可以 根据商品基本信息 异步去获取 促销、销售属性、规格参数等信息

    第三,图片信息和商品基本没有上下关联关系 可以同时异步获取

    第四,所以信息全部查询完成后一起返回

    @Test
    public void test16() throws ExecutionException, InterruptedException {
        //所有信息的汇总
        SkuiVo skuiVo = new SkuiVo();
        //查询基本信息(带返回值的异步)
        CompletableFuture<Skuinfo> infoFuture = CompletableFuture.supplyAsync(() -> {
            //假设查询到了商品基本信息
            Skuinfo skuinfo = new Skuinfo();
            skuinfo.setSpuId("1");
            skuinfo.setSpuId("2");
            skuinfo.setGuiId("3");
            skuiVo.setSkuinfo(skuinfo);
            return skuinfo;
        },executor);
    
        //查到基本信息后 异步同时去查 促销信息 规格信息 销售属性信息
        //拿到查基本信息任务的返回值 任务本身无需返回值
        CompletableFuture<Void> saleCxFuture = infoFuture.thenAcceptAsync((res) -> {
            String spuId = res.getSpuId();
            //拿到商品的销售id后查促销信息
            skuiVo.setSaleCx("促销信息");
        }, executor);
    
        CompletableFuture<Void> saleSxFuture = infoFuture.thenAcceptAsync((res) -> {
            String spuId = res.getSpuId();
            //拿到商品的销售id后查销售属性
            skuiVo.setSaleSx("销售属性信息");
        }, executor);
    
    
        CompletableFuture<Void> saleGgFuture = infoFuture.thenAcceptAsync((res) -> {
            String spuId = res.getSpuId();
            String guiId = res.getGuiId();
            //拿到商品的销售id和规格id 查商品规格信息
            skuiVo.setSaleGg("商品规格信息");
        }, executor);
    
        //查基本信息的时候 同时异步 也根据商品id 查商品图片信息
        //这个任务不需要返回值
        CompletableFuture<Void> imageFuture= CompletableFuture.runAsync(() -> {
            //查商品图片信息
            skuiVo.setImages("商品图片信息");
        }, executor);
    
        //等待所有任务都完成
        CompletableFuture.allOf(saleCxFuture,saleSxFuture,saleGgFuture,imageFuture).get();
    
        System.out.println(skuiVo);
    }
    
    • 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
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
  • 相关阅读:
    【VR开发】【Unity】【VRTK】3-VR项目设置
    19 Python的math模块
    秒懂Hadoop和Spark联系与区别
    点名(缺失的数字),剑指offer,力扣
    零基础学SQL(二、MYSQL数据类型)
    D. Navigation System(逆序最短路)
    git&&gitHub
    Node.js学习笔记
    vuejs之父子组件的通信【props】和【$emit】
    千峰商城-springboot项目搭建-78-购物车结算-查询购物车记录接口
  • 原文地址:https://blog.csdn.net/qq_45297578/article/details/133095569