CompletableFuture常见使用方法

package com.swl.juc.Executor;
import com.swl.juc.service.impl.NovelServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.concurrent.*;
import java.util.function.BiFunction;
import java.util.function.Function;

/**
 * thenApply/thenAccept/thenRun阻塞,区别:提交的任务类型不同
 * 1. thenApplyAsync/thenAcceptAsync/thenRunAsync非阻塞
 * 2. thenApply:Function签名(有入参和返回值),其中入参为前置任务的结果
 * thenAccept:Consumer签名(有入参但是没有返回值),其中入参为前置任务的结果
 * thenRun:Runnable签名(没有入参也没有返回值)
 **/

@Component
public class CompletableFutureTest {

    @Autowired
    private NovelServiceImpl novelService;

    private static ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
            5, 20, 5L, TimeUnit.SECONDS, new ArrayBlockingQueue<>(20)
    );

    public Integer getPrice() {
        return 10;
    }

    public Integer getNum() {
        return 2;
    }

    public void test1() throws InterruptedException, ExecutionException {
        CompletableFuture<Integer> ft1 = CompletableFuture.supplyAsync(() -> {
            System.out.println(Thread.currentThread().getName());
            return this.getPrice();
        }, threadPoolExecutor);

        CompletableFuture<Integer> ft2 = CompletableFuture.supplyAsync(() -> {
            System.out.println(Thread.currentThread().getName());
            return this.getNum();
        }, threadPoolExecutor);

        System.out.println(ft1.get() * ft2.get());
    }

    public void test2() throws InterruptedException, ExecutionException {
        CompletableFuture<Integer> ft1 = CompletableFuture.supplyAsync(() -> {
            System.out.println(Thread.currentThread().getName());
            return this.getPrice();
            // r为ft1的返回值,依赖ft1返回的结果
            //thenApply:Function签名(有入参和返回值),其中入参为前置任务的结果
            //thenAccept:Consumer签名(有入参但是没有返回值),其中入参为前置任务的结果
        }, threadPoolExecutor).thenApply(r -> {
            return this.getNum() * r;
        });

        System.out.println(ft1.get());

    }

    public void test3() throws InterruptedException, ExecutionException {
        long startTime = System.currentTimeMillis();
        CompletableFuture<Integer> ft1 = CompletableFuture.supplyAsync(() -> {
            System.out.println(Thread.currentThread().getName());
            return this.getPrice();
            // r为ft1的返回值,依赖ft1返回的结果
        }, threadPoolExecutor);

        CompletableFuture<Integer> ft2 = CompletableFuture.supplyAsync(() -> {
            System.out.println(Thread.currentThread().getName());
            return this.getNum();
        }, threadPoolExecutor);

        // ft3入参是ft1、ft2的处理结果
        //thenCombine主要用于没有前后依赖关系的任务进行连接
        CompletableFuture<Integer> ft3 = ft1.thenCombineAsync(ft2, new BiFunction<Integer, Integer, Integer>() {
            @Override
            public Integer apply(Integer price, Integer num) {
                return price * num;
            }
        }, threadPoolExecutor);

        System.out.println(ft3.get());
        System.out.println(System.currentTimeMillis() - startTime);

    }

    public void test4() throws InterruptedException, ExecutionException {
        CompletableFuture<Integer> ft1 = CompletableFuture.supplyAsync(() -> {
            System.out.println(Thread.currentThread().getName());
            return this.getPrice();
        }, threadPoolExecutor);

        CompletableFuture<Integer> ft2 = CompletableFuture.supplyAsync(() -> {
            System.out.println(Thread.currentThread().getName());
            return this.getNum();
        }, threadPoolExecutor);
        //都完成了计算才会执行下一步的操作(Runnable)
        ft1.runAfterBothAsync(ft2, () -> {
            System.out.println("以上两个任务均已完成");
        });
    }

    //thenCompose 方法允许你对两个 CompletionStage 进行流水线操作,第一个操作完成时,将其结果作为参数传递给第二个操作。
    public void test5() throws ExecutionException, InterruptedException {
        CompletableFuture<Integer> f = CompletableFuture.supplyAsync(() -> {
            return this.getPrice();
        }, threadPoolExecutor).thenCompose(new Function<Integer, CompletionStage<Integer>>() {
            @Override
            public CompletionStage<Integer> apply(Integer param) {
                return CompletableFuture.supplyAsync(() -> {
                    return getNum() * param;
                });
            }
        });
        System.out.println("thenCompose result : " + f.get());
    }

    public static void main(String[] args) throws InterruptedException, ExecutionException {
        CompletableFutureTest completableFutureTest = new CompletableFutureTest();
//        completableFutureTest.test1();
//        Thread.sleep(2000);
//        completableFutureTest.test2();
        completableFutureTest.test5();
    }


}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值