CompletableFuture(异步编程详解)

CompletableFuture

一、runAsync

1.1、runAsunc(一个Runnable接口)

package com.thread.study.jdksyn;

import java.util.concurrent.*;

/**
 * @ClassName
 * @Description TODO
 * @Author ZQS
 * @Date 2020/9/9 0009 14:29
 * @Version 1.0
 **/
public class CompletableFutureTest {

    public static void main(String[] args) throws ExecutionException, InterruptedException {

		
        CompletableFuture<Void> voidCompletableFuture = CompletableFuture.runAsync(() -> {
            System.out.println("当前线程为:" + Thread.currentThread().getName());
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        voidCompletableFuture.get();
        System.out.println("运行后再运行这个结果");


    }
}

1.2、runAsync(一个Runnable接口,自定义线程池)

package com.thread.study.jdksyn;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @ClassName
 * @Description TODO
 * @Author ZQS
 * @Date 2020/9/9 0009 14:29
 * @Version 1.0
 **/
public class CompletableFutureTest {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        /**
         * 自定义线程池
         * ThreadFactory接口中只有一个方法
         * Thread newThread(Runnable r);
         */
        AtomicInteger atomicInteger = new AtomicInteger(0);
        ExecutorService executorService = Executors.newFixedThreadPool(2,(runnable)->{
            Thread thread=new Thread(runnable);
            thread.setName("zqs_"+atomicInteger);
            return thread;
        });

        /**
         * 使用自定义线程池做完成异步编程
         */
        CompletableFuture<Void> voidCompletableFuture = CompletableFuture.runAsync(() -> {
            System.out.println("当前线程为:" + Thread.currentThread().getName());
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, executorService);
        voidCompletableFuture.get();
        System.out.println("运行后再运行这个结果");
        executorService.shutdown();

    }
}

二、supplyAsync(有返回结果)

用法和runAsync 一样

有一个参
有两个参

package com.thread.study.jdksyn;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @ClassName
 * @Description TODO
 * @Author ZQS
 * @Date 2020/9/9 0009 15:29
 * @Version 1.0
 **/
public class CompletableFutureTest {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        /**
         * 自定义线程池
         */
        AtomicInteger atomicInteger = new AtomicInteger(0);
        ExecutorService executorService = Executors.newFixedThreadPool(2, (runnable) -> {
            Thread thread = new Thread(runnable);
            thread.setName("zqs_" + atomicInteger);
            return thread;
        });

        /**
         * 使用自定义线程池做完成异步编程supply(运输)
         */
        CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(() -> {
            System.out.println("执行任务1");
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return "任务1完成";
        }, executorService);

        String s = completableFuture.get();
        System.out.println(s);

    }
}

三、thenApply 和 thenApplyAsync

thenApply (两个任务) 使用的线程是一个

thenApplyAsync(两个任务)使用的线程可以不是一个

特点:都是顺序执行,都有返回值

package com.thread.study.jdksyn;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @ClassName
 * @Description TODO
 * @Author ZQS
 * @Date 2020/9/9 0009 15:29
 * @Version 1.0
 **/
public class CompletableFutureTest {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        /**
         * 自定义线程池
         */
        AtomicInteger atomicInteger = new AtomicInteger(0);
        ExecutorService executorService = Executors.newFixedThreadPool(2, (runnable) -> {
            Thread thread = new Thread(runnable);
            thread.setName("zqs_" + atomicInteger);
            return thread;
        });

        /**
         * 使用自定义线程池做完成异步编程supply(运输)
         */
        CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(() -> {
            try {
                Thread.sleep(2000);
                System.out.println("任务1线程名:"+Thread.currentThread().getName());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return "aaa";
        }, executorService).thenApplyAsync(s->{
            String s1 = s.toUpperCase();
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            System.out.println("任务2线程名:"+Thread.currentThread().getName());
            return s1;
        });

        String s = completableFuture.get();
        System.out.println(s);

    }
}

测试结果:
在这里插入图片描述

四、thenAccept()和 thenAcceptAsync()

跟上面的方法类似,只不过没有返回值,参数是消费者接口

package com.thread.study.jdksyn;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @ClassName
 * @Description TODO
 * @Author ZQS
 * @Date 2020/9/9 0009 15:29
 * @Version 1.0
 **/
public class CompletableFutureTest {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        /**
         * 自定义线程池
         */
        AtomicInteger atomicInteger = new AtomicInteger(0);
        ExecutorService executorService = Executors.newFixedThreadPool(2, (runnable) -> {
            Thread thread = new Thread(runnable);
            thread.setName("zqs_" + atomicInteger);
            return thread;
        });

        /**
         * 使用自定义线程池做完成异步编程supply(运输)
         */
        CompletableFuture<Void> completableFuture = CompletableFuture.supplyAsync(() -> {
            try {
                Thread.sleep(2000);
                System.out.println("任务1线程名:"+Thread.currentThread().getName());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return "aaa";
        }, executorService).thenAcceptAsync(s->{
            String s1 = s.toUpperCase();
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            System.out.println("任务2线程名:"+Thread.currentThread().getName());
        });

        Void aVoid = completableFuture.get();
        System.out.println(aVoid);

    }
}

在这里插入图片描述

五、thenRun()

跟上面方法类似,只不过拿不到参数,参数为一个runnable对象

	executorService).thenRun(()->{
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            System.out.println("任务2线程名:"+Thread.currentThread().getName());

六、thenCompose(然后组装)

第一个任务完成(参数)然后给第二个任务

所以两者是有关系的

public class CompletableFutureTest {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        CompletableFuture<String> completableFuture = getProjectId().thenCompose(id -> getProjectById(id));
        System.out.println("获得最终的结果为:"+completableFuture.get());
    }
    //根据某某条件获得商品id
    private static CompletableFuture<Integer> getProjectId(){
        return CompletableFuture.supplyAsync(()->{
            System.out.println("当前执行的线程为:"+Thread.currentThread().getName());
            System.out.println("这里面执行了非常多的操作然后得到了一个项目ID");
            return 10;
        });
    }
    //根据上面获得商品id去查询商品的详细信息
    private static CompletableFuture<String> getProjectById(int id){
        return CompletableFuture.supplyAsync(()->{
            System.out.println("当前执行的线程为:"+Thread.currentThread().getName());
            System.out.println("这里面执行了非常多的操作然后根据id获得了商品的详细信息,id:"+id);
            return "华为手机";
                });
    }

}

七、thenCombine()

组装没有联系

看谁的速度快先执行完谁

package com.thread.study.jdksyn;

import java.util.concurrent.*;

/**
 * @ClassName
 * @Description TODO
 * @Author ZQS
 * @Date 2020/9/9 0009 15:29
 * @Version 1.0
 **/
public class CompletableFutureTest {

    public static void main(String[] args) throws ExecutionException, InterruptedException {

        CompletableFuture<Integer> integerCompletableFuture1 = CompletableFuture.supplyAsync(() -> {
            try {
                Thread.sleep(2000);
                System.out.println("任务1");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return 1;
        });

        CompletableFuture<Integer> integerCompletableFuture2 = CompletableFuture.supplyAsync(() -> {
            try {
                Thread.sleep(1000);
                System.out.println("任务2");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return 2;
        });

        CompletableFuture<Integer> integerCompletableFuture = integerCompletableFuture1.thenCombine(integerCompletableFuture2, (id1, id2) -> {
            return id1 + id2;
        });
        System.out.println(integerCompletableFuture.get());

    }

}

在这里插入图片描述

八、allOf()

全部执行完成才执行下面的

package com.thread.study.jdksyn;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @ClassName
 * @Description TODO
 * @Author ZQS
 * @Date 2020/9/9 0009 15:29
 * @Version 1.0
 **/
public class CompletableFutureTest {

    private static final AtomicInteger ATOMIC_INTEGER = new AtomicInteger(0);
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        CompletableFuture<Void> completableFuture1 = CompletableFuture.runAsync(() -> {
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("第一个task");});
        CompletableFuture<Void> completableFuture2 = CompletableFuture.runAsync(() -> {
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("第二个task");});
        CompletableFuture<Void> completableFuture3 = CompletableFuture.runAsync(() -> {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("第三个task");});
        //希望上面三个任务都完成才继续后面
        CompletableFuture<Void> allOf = CompletableFuture.allOf(completableFuture1, completableFuture2, completableFuture3);
        allOf.join();
        System.out.println("三个任务全部结束,现在可以继续后面的工作");
    }
}

在这里插入图片描述

九、anyOf()

和上面用法一样

但是有一个任务完成就执行下面的任务

十、异常处理

10.1、在任务链执行完加一个 .exceptionally()

有返回值

package com.thread.study.jdksyn;

import java.util.concurrent.*;

/**
 * @ClassName
 * @Description TODO
 * @Author ZQS
 * @Date 2020/9/9 0009 15:29
 * @Version 1.0
 **/
public class CompletableFutureTest {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        CompletableFuture<String> voidCompletableFuture = CompletableFuture.supplyAsync(() -> {
            System.out.println("supplyAsync方法执行");
            throw new RuntimeException("在supplyAsync方法中出现异常");
        }).thenApply(s -> {
            System.out.println("因为上面出现了异常我就不会执行了");
            return "不会执行";
        }).exceptionally(e-> {
            System.out.println(Thread.currentThread().getName()+"执行过程中出现了异常了"+e);
            return "凉凉";
        });
        System.out.println(voidCompletableFuture.get());;
        System.out.println("出现异常不执行了");
    }
}

十一、handle()

有没有异常都会执行,可以根据判断来返回不同的东西

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值