测试CompletableFutrue的使用

很多场景下,获取线程运行的结果,使用execute方法去提交任务是无法获得结果的,这时候会改用submit方法去提交,以便获得线程运行的结果。
而submit方法返回的就是Future,一个未来对象。 使用future.get() 方法去获取线程执行结果,包括如果出现异常,也会随get方法抛出。
future.get()方法去取得线程执行结果时,get方法是阻塞的,当主线程执行到get()方法,当前线程会去等待异步任务执行完成,换言之,异步的效果在我们使用get()拿结果时,会变得无效。

JDK1.8才新加入的一个实现类CompletableFuture,实现了Future, CompletionStage两个接口。在异步计算中,两个计算任务相互独立,但是任务二又依赖于任务一的结果。这种情况下,靠Future是解决不了,而CompletableFuture则可以实现。

下面是对ComletableFutrue的测试,函数的说明都在注释中

package com.iscas.common.tools.thread;

import org.jetbrains.annotations.NotNull;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 *
 * @author zhuquanwen
 * @vesion 1.0
 * @date 2021/1/30 15:50
 * @since jdk1.8
 */
@RunWith(JUnit4.class)
public class CompletableFutrueTests {
    private ThreadPoolExecutor threadPoolExecutor = null;
    private AtomicInteger atomicInteger = new AtomicInteger(1);

    @Before
    public void before() {
        threadPoolExecutor = new ThreadPoolExecutor(2, 2, 0, TimeUnit.MILLISECONDS,
                new SynchronousQueue<Runnable>(), new ThreadFactory() {
            @Override
            public Thread newThread(@NotNull Runnable r) {
                return new Thread(r, "线程-" + atomicInteger.getAndIncrement());
            }
        });
    }


    /**
     * 测试使用CompletableFuture无返回值
     * */
    @Test
    public void test() {
        CompletableFuture<Void> completableFuture = CompletableFuture.runAsync(() -> {
            System.out.println("没有返回值");
        }, threadPoolExecutor);
    }

    /**
     * 测试使用CompletableFuture有返回值
     * */
    @Test
    public void test2() throws ExecutionException, InterruptedException {
        CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(() -> {
            System.out.println("有返回值");
            return "没返回值";
        }, threadPoolExecutor);
        String s = completableFuture.get();
        System.out.println("执行完了");
    }

    /**
     * 测试使用completableFutrue的whenComplete方法
     * */
    @Test
    public void test3() throws InterruptedException {
        CompletableFuture.supplyAsync(() -> {
            try {
                TimeUnit.MILLISECONDS.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("测试whenComplete");
            return 1;
        }).whenComplete((r, e) -> {
            System.out.println("执行完了");
        });
        System.out.println("任务提交");
        Thread.currentThread().join();
    }

    /**
     * 测试使用CompleteableFuture的exceptionally方法
     * */
    @Test
    public void test4() throws InterruptedException {
        CompletableFuture.supplyAsync(() -> {
            try {
                TimeUnit.MILLISECONDS.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("测试exceptionally");
            throw new RuntimeException("异常");
        }).exceptionally(e -> {
            System.out.println("出现了异常");
            e.printStackTrace();
            return 2;
        });
        System.out.println("任务提交");
        Thread.currentThread().join();
    }

    /**
     * 测试使用CompleteableFuture的exceptionally方法和whenComplete方法同时使用
     * 谁在前,谁先执行,而且不管有没有异常,whenComplete都会执行
     * */
    @Test
    public void test5() throws InterruptedException {
        CompletableFuture.supplyAsync(() -> {
            try {
                TimeUnit.MILLISECONDS.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("测试whenComplete和exceptionally混合使用");
            throw new RuntimeException("111");
        }).exceptionally(e -> {
            System.out.println("出现了异常");
            return 2;
        }).whenComplete((r, e) -> {
            System.out.println("结束了");
        });
        System.out.println("任务提交");
        Thread.currentThread().join();
    }

    /**
     * 测试使用CompleteableFuture的whenCompleteAsync方法,
     * 此方法让结果给不同得线程执行
     * */
    @Test
    public void test6() throws InterruptedException {
        CompletableFuture.supplyAsync(() -> {
            try {
                TimeUnit.MILLISECONDS.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName());
            return "测试whenCompleteAsync";
        }, threadPoolExecutor).whenCompleteAsync((r, e) -> {
            System.out.println(Thread.currentThread().getName());
            System.out.println("完成了");
        }, threadPoolExecutor);
        System.out.println("任务提交");
        Thread.currentThread().join();
    }

    /**
     * 测试使用CompleteableFuture的thenApply方法,
     * 此方法适用于某个线程依赖另一个线程的执行结果,
     * 两个线程使用一个线程池
     * */
    @Test
    public void test7() throws InterruptedException {
        CompletableFuture.supplyAsync(() -> {
            try {
                TimeUnit.MILLISECONDS.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName());
            return 4;
        }, threadPoolExecutor).thenApply(r -> r + 1).whenComplete((r, e) -> {
            System.out.println(r);
            System.out.println("完成了");
        });
        System.out.println("任务提交");
        Thread.currentThread().join();
    }

    /**
     * 测试使用CompleteableFuture的thenApplyAsync方法,
     * 此方法适用于某个线程依赖另一个线程的执行结果,
     * 两个线程可以使用不同的线程池
     * */
    @Test
    public void test8() throws InterruptedException {
        CompletableFuture.supplyAsync(() -> {
            try {
                TimeUnit.MILLISECONDS.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName());
            return 4;
        }, threadPoolExecutor).thenApplyAsync(r -> {
            System.out.println(Thread.currentThread().getName());
            return r + 1;
        }, threadPoolExecutor).whenComplete((r, e) -> {
            System.out.println(r);
            System.out.println("完成了");
        });
        System.out.println("任务提交");
        Thread.currentThread().join();
    }

    /**
     * 测试使用CompleteableFuture的handle方法,
     * 此方法适用于某个线程依赖另一个线程的执行结果,可以处理异常
     * 两个线程使用一个线程池
     * */
    @Test
    public void test9() throws InterruptedException {
        CompletableFuture.supplyAsync(() -> {
            try {
                TimeUnit.MILLISECONDS.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName());
            return 4;
        }, threadPoolExecutor).handle((r, e) -> r + 1).whenComplete((r, e) -> {
            System.out.println(r);
            System.out.println("完成了");
        });
        System.out.println("任务提交");
        Thread.currentThread().join();
    }

    /**
     * 测试使用CompleteableFuture的thenApplyAsync方法,
     * 此方法适用于某个线程依赖另一个线程的执行结果,
     * 两个线程可以使用不同的线程池
     * */
    @Test
    public void test10() throws InterruptedException {
        CompletableFuture.supplyAsync(() -> {
            try {
                TimeUnit.MILLISECONDS.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName());
            throw new RuntimeException("111");
        }, threadPoolExecutor).handleAsync((r, e) -> {
            System.out.println(Thread.currentThread().getName());
            System.out.println(e);
            if (e == null) {
                return 1;
            } else {
                return -1;
            }
        }, threadPoolExecutor).whenComplete((r, e) -> {
            System.out.println(r);
            System.out.println("完成了");
        });
        System.out.println("任务提交");
        Thread.currentThread().join();
    }

    /**
     * 测试使用CompleteableFuture的thenCombine方法,
     * 此方法适用于两个future的结果合并,
     * 两个线程用同一个线程池
     * */
    @Test
    public void test11() throws InterruptedException {
        CompletableFuture<Integer> future1 = CompletableFuture.supplyAsync(() -> {
            try {
                TimeUnit.MILLISECONDS.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName());
            throw new RuntimeException("111");
        }, threadPoolExecutor).handleAsync((r, e) -> {
            System.out.println(Thread.currentThread().getName());
            System.out.println(e);
            if (e == null) {
                return 1;
            } else {
                return -1;
            }
        }, threadPoolExecutor).whenComplete((r, e) -> {
            System.out.println(r);
            System.out.println("完成了");
        });
        CompletableFuture<Integer> future2 = CompletableFuture.supplyAsync(() -> {
            return 1;
        });
        future1.thenCombine(future2, (r1, r2) -> {
            return r1 + r2;
        }).whenComplete((r, e) -> {
            System.out.println("结果为:" + r);
        });
        System.out.println("任务提交");
        Thread.currentThread().join();
    }

    /**
     * 测试使用CompleteableFuture的thenCombineAsync方法,
     * 此方法适用于两个future的结果合并,
     * 两个线程用同一个线程池
     * */
    @Test
    public void test12() throws InterruptedException {
        CompletableFuture<Integer> future1 = CompletableFuture.supplyAsync(() -> {
            try {
                TimeUnit.MILLISECONDS.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName());
            throw new RuntimeException("111");
        }, threadPoolExecutor).handleAsync((r, e) -> {
            System.out.println(Thread.currentThread().getName());
            System.out.println(e);
            if (e == null) {
                return 1;
            } else {
                return -1;
            }
        }, threadPoolExecutor).whenComplete((r, e) -> {
            System.out.println(r);
            System.out.println("完成了");
        });
        CompletableFuture<Integer> future2 = CompletableFuture.supplyAsync(() -> {
            return 1;
        });
        future1.thenCombineAsync(future2, (r1, r2) -> {
            return r1 + r2;
        }, threadPoolExecutor).whenComplete((r, e) -> {
            System.out.println("结果为:" + r);
        });
        System.out.println("任务提交");
        Thread.currentThread().join();
    }

    /**
     * 测试使用CompleteableFuture的thenAcceptBoth方法,
     * 此方法适用于两个future的结果合并,与thenCombine的区别是没有返回值
     * 两个线程用同一个线程池, 如果是用不同谢娜城池使用thenAcceptBothAsync,不单独写测试了
     * */
    @Test
    public void test13() throws InterruptedException {
        CompletableFuture<Integer> future1 = CompletableFuture.supplyAsync(() -> {
            try {
                TimeUnit.MILLISECONDS.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName());
            throw new RuntimeException("111");
        }, threadPoolExecutor).handleAsync((r, e) -> {
            System.out.println(Thread.currentThread().getName());
            System.out.println(e);
            if (e == null) {
                return 1;
            } else {
                return -1;
            }
        }, threadPoolExecutor).whenComplete((r, e) -> {
            System.out.println(r);
            System.out.println("完成了");
        });
        CompletableFuture<Integer> future2 = CompletableFuture.supplyAsync(() -> {
            return 1;
        });
        future1.thenAcceptBoth(future2, (r1, r2) -> {
            System.out.println("结果为:" + (r1 + r2));
        }).whenComplete((r, e) -> {
            System.out.println("结果为:" + r);
        });
        System.out.println("任务提交");
        Thread.currentThread().join();
    }

    /**
     * 测试使用CompleteableFuture的allOf方法,
     * 此方法适用于等待多个future的执行结果
     *
     * */
    @Test
    public void test14() throws InterruptedException {
        int[] count = new int[1];
        CompletableFuture[] completableFutures = Arrays.asList(1, 1, 12, 34, -1, 5, -13).stream().map(i ->
                CompletableFuture.supplyAsync(() -> i).whenComplete((r, e) -> {
                    try {
                        TimeUnit.MILLISECONDS.sleep(200);
                    } catch (InterruptedException interruptedException) {
                        interruptedException.printStackTrace();
                    }
                    System.out.println("一个线程完成,结果为:" + r);
                    count[0] += r;
                })).toArray(CompletableFuture[]::new);
        CompletableFuture.allOf(completableFutures).whenCompleteAsync((r, e) -> {
            System.out.println("全部完成,结果为:" + count[0]);
        });

        System.out.println("任务提交");
        Thread.currentThread().join();
    }

}

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值