java.util.concurrent之CompletableFuture基础用法

CompletableFuture类主要用于线程的异步执行,主要方法包括:

1 runAsync() 异步执行无返回值

2 supplyAsync() 异步执行有返回值

3 thenApply ()第二个线程依赖第一个的执行结果

4 thenCombine() 第三个线程依赖第一个和第二个线程的执行结果

5 allOf ()最终结果依赖多个线程的执行结果

6 anyOf ()任何一个线程执行结束,都可以触发最终操作

详细用法如下

package com.zhang.jiu.learn.complatable;

import org.junit.jupiter.api.Test;

import java.util.concurrent.*;

public class CompletableTest {
    @Test
    public void test1 () throws Exception{
        ExecutorService executorService = Executors.newFixedThreadPool(5);

        //1 CompletableFuture 无返回结果
        CompletableFuture.runAsync(new Task1(),executorService);
        //2 CompletableFuture 有返回结果
        CompletableFuture<Integer> future1 = CompletableFuture.supplyAsync(() -> {
            int a = 5;
            int b = 5;
            return a + b;
        });
        //future1 的执行结果
        Integer result = future1.get(10, TimeUnit.SECONDS);
        System.out.println(result);

        //3 future2 依赖future1的执行结果
        CompletableFuture<Integer> future2 = future1.thenApply(future1Result -> {
            return future1Result + 4;
        });
        System.out.println(future2.get());

        CompletableFuture<Integer> future3 = CompletableFuture.supplyAsync(() -> {
            int a = 5;
            int b = 5;
            return a * b;
        });
        //4 future4 依赖 future1 future3 的结果
        CompletableFuture<Integer> future4 = future3.thenCombine(future1, (future1Result, future3Result) -> {
            return future1Result+future3Result;
        });
        System.out.println(future4.get());

        CompletableFuture<Integer> future5 = CompletableFuture.supplyAsync(() -> {
            int a = 5;
            int b = 5;
            return a / b;
        });
        //5 future6 等待 future1 future3 future5的结果
        CompletableFuture<Void> future6 = CompletableFuture.allOf(future1, future3, future5);
        CompletableFuture<Integer> futureFinal = future6.thenApply(item -> {
            Integer result1 = future1.join();
            Integer result3 = future3.join();
            Integer result5 = future5.join();

            return result1 + result3 + result5;
        });
        //5 future1 future3 future5任何一个执行结束了,执行 future7
        CompletableFuture<Object> future7 = CompletableFuture.anyOf(future1, future3, future5);
        CompletableFuture<String> futureFinal2 = future7.thenApply(item -> {

            return "future1 future3 future5 有一个执行结束了,我触发了";
        });

        System.out.println(futureFinal2.get());
    }

    public static class Task1 implements Runnable {

        @Override
        public void run() {
            System.out.println("异步任务Task1执行了");
        }
    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值