CompletableFuture

import lombok.extern.slf4j.Slf4j;
import org.junit.Test;

import java.util.concurrent.*;

@Slf4j
public class CompletableFutureTest {
    ExecutorService EXECUTOR = new ThreadPoolExecutor(5, 20, 0L,
            TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(200), new ThreadPoolExecutor.CallerRunsPolicy());

    /**
     * runAsync 无返回值
     * 如果在参数中包含指定executor的话,任务在这个executor执行;
     * 如果没有指定executor,在ForkJoinPool.commonPool()线程池中运行
     */
    @Test
    public void runAsyncMethod() {
        CompletableFuture<Void> completableFuture = CompletableFuture.runAsync(() -> {
            System.out.println("current thread:" + Thread.currentThread().getId());
            int i = 10 / 2;
            System.out.println("result:" + i);
        }, EXECUTOR);
    }

    /**
     * supplyAsync有返回值
     * 如果在参数中包含指定executor的话,任务在这个executor执行;
     * 如果没有指定executor,在ForkJoinPool.commonPool()线程池中运行
     * whenComplete 能感知异常,能感知结果,但没方法给返回值
     * exceptionally能感知异常,不能感知结果,能给返回值。相当于,如果出现异常就返回这个值
     *
     * @throws ExecutionException
     * @throws InterruptedException
     */
    @Test
    public void supplyAsyncMethod() throws ExecutionException, InterruptedException {
        CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
            System.out.println("current thread:" + Thread.currentThread().getId());
            //int i = 10 / 2;
            int i = 10 / 0;
            System.out.println("result:" + i);
            return i;
        }, EXECUTOR).whenComplete((res, exception) -> {
            System.out.println("async task end,result:" + res + ";exception:" + exception);
        }).exceptionally(throwable -> {
            return 10;
        });
        System.out.println("result:" + future.get());
    }

    /**
     * supplyAsync有返回值
     * 如果在参数中包含指定executor的话,任务在这个executor执行;
     * 如果没有指定executor,在ForkJoinPool.commonPool()线程池中运行
     * handle能拿到返回结果,也能的到异常信息,也能修改返回值
     * 带有async的方法,如果指定线程池,就使用指定的线程池,如果没有指定线程池,就使用默认的线程池
     *
     * @throws ExecutionException
     * @throws InterruptedException
     */
    @Test
    public void supplyAsyncMethodByHandle() throws ExecutionException, InterruptedException {
        CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
            System.out.println("current thread:" + Thread.currentThread().getId());
            int i = 10 / 4;
            System.out.println("result:" + i);
            return i;
        }, EXECUTOR).handle((res, exception) -> {
            if (null != exception) {
                return 0;
            } else {
                return res * 2;
            }
        });
        System.out.println("result:" + future.get());
    }

    /**
     * 任务线性化
     * thenRunAsync:不能接收上一次的执行结果,也没返回值
     *
     * @throws InterruptedException
     */
    @Test
    public void taskSerial() throws InterruptedException {
        CompletableFuture.supplyAsync(() -> {
            System.out.println("current thread:" + Thread.currentThread().getId());
            int i = 10 / 4;
            System.out.println("result:" + i);
            return i;
        }, EXECUTOR).thenRunAsync(() -> {
            System.out.print("task 2 start....");
        }, EXECUTOR);
    }

    /**
     * 任务线性化
     * thenAcceptAsync:能接收上一次的执行结果,但没返回值
     */
    @Test
    public void taskSerialAccept() {
        CompletableFuture.supplyAsync(() -> {
            System.out.println("current thread:" + Thread.currentThread().getId());
            int i = 10 / 4;
            System.out.println("result:" + i);
            return i;
        }, EXECUTOR).thenAcceptAsync(res -> {
            System.out.print("task 2 start...." + res);
        }, EXECUTOR);
    }

    /**
     * 任务线性化
     * 前面两个任务都完成,才执行任务3
     * thenApplyAsync:能接收上一次的执行结果,有可以有返回值
     */
    @Test
    public void taskSerialApply() throws ExecutionException, InterruptedException {
        CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
            System.out.println("current thread:" + Thread.currentThread().getId());
            int i = 10 / 4;
            System.out.println("result:" + i);
            return i;
        }, EXECUTOR).thenApplyAsync(res -> {
            System.out.println("task 2 start...." + res);
            return "hello:" + res + "\n";
        }, EXECUTOR);
        System.out.print("result:" + future.get());
    }

    /**
     * runAfterBothAsync
     * 任务1和任务2都完成后,在执行任务3,不感知任务1,2的结果,也没有返回值
     *
     * @throws InterruptedException
     */
    @Test
    public void taskBianPai() throws InterruptedException {
        CompletableFuture<Integer> future1 = CompletableFuture.supplyAsync(() -> {
            System.out.println("task 1:" + Thread.currentThread().getId());
            int i = 10 / 4;
            System.out.println("task 1 end...");
            return i;
        }, EXECUTOR);
        CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> {
            System.out.println("task 2:" + Thread.currentThread().getId());
            try {
                Thread.sleep(3000);
                System.out.println("task 2 end...");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return "hello";
        }, EXECUTOR);
        future1.runAfterBothAsync(future2, () -> {
            System.out.println("task 3 start...");
        }, EXECUTOR);
    }

    /**
     * thenAcceptBothAsync
     * 任务1和任务2都完成后,在执行任务3,感知任务1,2的结果,也没有返回值
     */
    @Test
    public void taskBianPaiAccept() {
        CompletableFuture<Integer> future1 = CompletableFuture.supplyAsync(() -> {
            System.out.println("task 1:" + Thread.currentThread().getId());
            int i = 10 / 4;
            System.out.println("task 1 end...");
            return i;
        }, EXECUTOR);
        CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> {
            System.out.println("task 2:" + Thread.currentThread().getId());
            System.out.println("task 2 end...");
            try {
                Thread.sleep(3000);
                System.out.println("task 2 end...");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return "hello";
        }, EXECUTOR);
        CompletableFuture<Void> completableFuture = future1.thenAcceptBothAsync(future2, (f1, f2) -> {
            System.out.println(f1);
            System.out.println(f2);
            System.out.println("task 3 start...,f1:" + f1 + ",f2:" + f2);
        }, EXECUTOR);
    }

    /**
     * thenCombineAsync
     * 任务1和任务2都完成后,在执行任务3,感知任务1,2的结果,可以自己带返回值
     */
    @Test
    public void taskBianPaiCombine() throws ExecutionException, InterruptedException {
        CompletableFuture<Integer> future1 = CompletableFuture.supplyAsync(() -> {
            System.out.println("task 1:" + Thread.currentThread().getId());
            int i = 10 / 4;
            System.out.println("task 1 end...");
            return i;
        }, EXECUTOR);
        CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> {
            System.out.println("task 2:" + Thread.currentThread().getId());
            System.out.println("task 2 end...");
            try {
                Thread.sleep(3000);
                System.out.println("task 2 end...");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return "hello";
        }, EXECUTOR);
        CompletableFuture<String> completableFuture = future1.thenCombineAsync(future2, (f1, f2) -> {
            return "task 3 start...,f1:" + f1 + ",f2:" + f2;
        }, EXECUTOR);
        System.out.println(completableFuture.get());
    }

    /**
     * 三任务组合,前两个任务只要有一个完成,就执行任务3
     */

    /**
     * thenCombineAsync
     * 两个任务只要有一个完成,就执行任务3,不感知结果,自己没返回值
     */
    @Test
    public void taskRun() throws ExecutionException, InterruptedException {
        CompletableFuture<Integer> future1 = CompletableFuture.supplyAsync(() -> {
            System.out.println("task 1:" + Thread.currentThread().getId());
            int i = 10 / 4;
            System.out.println("task 1 end...");
            return i;
        }, EXECUTOR);
        CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> {
            System.out.println("task 2:" + Thread.currentThread().getId());
            System.out.println("task 2 end...");
            try {
                Thread.sleep(3000);
                System.out.println("task 2 end...");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return "hello";
        }, EXECUTOR);
        CompletableFuture<Void> completableFuture = future1.runAfterEitherAsync(future2, () -> {
            System.out.println("task 3 start.....");
        }, EXECUTOR);
    }

    /**
     * acceptEitherAsync
     * 两个任务只要有一个完成,就执行任务3,感知结果,自己没返回值
     */
    @Test
    public void taskAccept() {
        CompletableFuture<String> future1 = CompletableFuture.supplyAsync(() -> {
            System.out.println("task 1:" + Thread.currentThread().getId());
            int i = 10 / 4;
            System.out.println("task 1 end...");
            return String.valueOf(i);
        }, EXECUTOR);
        CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> {
            System.out.println("task 2:" + Thread.currentThread().getId());
            System.out.println("task 2 end...");
            try {
                Thread.sleep(3000);
                System.out.println("task 2 end...");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return "hello";
        }, EXECUTOR);
        CompletableFuture<Void> completableFuture = future1.acceptEitherAsync(future2, (res) -> {
            System.out.println("task 3 start....." + res);
        }, EXECUTOR);
    }

    /**
     * applyToEitherAsync
     * 两个任务只要有一个完成,就执行任务3,感知结果,自己有返回值
     */
    @Test
    public void taskApply() throws ExecutionException, InterruptedException {
        CompletableFuture<String> future1 = CompletableFuture.supplyAsync(() -> {
            System.out.println("task 1:" + Thread.currentThread().getId());
            int i = 10 / 4;
            System.out.println("task 1 end...");
            return String.valueOf(i);
        }, EXECUTOR);
        CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> {
            System.out.println("task 2:" + Thread.currentThread().getId());
            System.out.println("task 2 end...");
            try {
                Thread.sleep(3000);
                System.out.println("task 2 end...");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return "hello";
        }, EXECUTOR);
        CompletableFuture<String> completableFuture = future1.applyToEitherAsync(future2, (res) -> {
            System.out.println("task 3 start....." + res);
            return "task 3 end...";
        }, EXECUTOR);
        System.out.println(completableFuture.get());
    }

    /**
     * 多任务组合
     */
    /**
     * allOf 所有任务都执行完
     *
     * @throws ExecutionException
     * @throws InterruptedException
     */
    @Test
    public void multiTaskCombine() throws ExecutionException, InterruptedException {
        CompletableFuture<String> productInfo = CompletableFuture.supplyAsync(() -> {
            System.out.println("product info");
            return "product info";
        }, EXECUTOR);
        CompletableFuture<String> productProperty = CompletableFuture.supplyAsync(() -> {
            System.out.println("product property");
            return "product property";
        }, EXECUTOR);
        CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
            try {
                Thread.sleep(3000);
                System.out.println("查询商品介绍信息");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return "华为...";
        }, EXECUTOR);
        CompletableFuture<Void> allOf = CompletableFuture.allOf(productInfo, productProperty, future);
        allOf.get();
    }

    /**
     * anyOf 其中有一个任务执行完就可以
     *
     * @throws ExecutionException
     * @throws InterruptedException
     */
    @Test
    public void multiTaskCombineAny() throws ExecutionException, InterruptedException {
        CompletableFuture<String> productInfo = CompletableFuture.supplyAsync(() -> {
            System.out.println("product info");
            return "product info";
        }, EXECUTOR);
        CompletableFuture<String> productProperty = CompletableFuture.supplyAsync(() -> {
            System.out.println("product property");
            return "product property";
        }, EXECUTOR);
        CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
            try {
                Thread.sleep(3000);
                System.out.println("查询商品介绍信息");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return "华为...";
        }, EXECUTOR);
        CompletableFuture<Object> anyOf = CompletableFuture.anyOf(productInfo, productProperty, future);
        anyOf.get();
    }


}

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 199,711评论 5 468
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 83,932评论 2 376
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 146,770评论 0 330
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 53,799评论 1 271
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,697评论 5 359
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,069评论 1 276
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,535评论 3 390
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,200评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,353评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,290评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,331评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,020评论 3 315
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,610评论 3 303
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,694评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,927评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,330评论 2 346
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 41,904评论 2 341

推荐阅读更多精彩内容