Java异步CompletableFuture

package integral;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

/**
 * 
 * @author YangTG
 * 异步执行
 */
public class CompletableFutureDemo {
	
	public static void any(){
		System.out.println("runAsync..");
	}
	
	public static String any1(){
		return "supplyAsync...";
	}
	
	public static void main(String[] args) throws InterruptedException, ExecutionException {
		
		List<CompletableFuture> list = new ArrayList<>();
		int i=0;
		//没有返回值异步
		/*while(i<5){
			CompletableFuture<Void> comp = new CompletableFuture<>().runAsync(()->{
				CompletableFutureDemo.any();
				
			});
			list.add(comp);
			i++;
		}*/
		CompletableFuture<String> future =null;
		//有返回值
		while(i<5){
			 future = new CompletableFuture<>().supplyAsync(()->{
				return CompletableFutureDemo.any1();
			});
			list.add(future);
			i++;
		}
		//之前执行
		future.thenRun(()->{
			CompletableFutureDemo.any();
		});
		System.out.println("执行完毕");
		list.forEach(a->{
			try {
				System.out.println(a.get());
			} catch (Exception e) {
				e.printStackTrace();
			} 
		});
	}
}

执行结果

runAsync..
执行完毕
supplyAsync...
supplyAsync...
supplyAsync...
supplyAsync...
supplyAsync...
package CompletableFuture;

import java.util.concurrent.CompletableFuture;

public class Demo {

    public static void main(String[] args) throws Exception {
        //demo1();
        //demo2();
        //demo3();
        //demo4();
        //demo5();
        demo6();
    }

    /**
     * 异步回调 没有返回值
     *
     * @throws Exception
     */
    public static void demo1() throws Exception {
        // 创建异步返回任务
        CompletableFuture<String> cf = CompletableFuture.supplyAsync(() -> {
            return "hello";
        });
        //创建不带返回值异步任务 cf2,该任务的需要cf的结果作为异步任务的参数
        CompletableFuture<Void> cf2 = cf.thenAcceptAsync(result -> {
            String s = result + " thenAcceptAsync";
            System.out.println(s);
        });
        cf2.get();
        CompletableFuture<Void> cf3 = cf.thenAccept(result -> {
            String s = result + " thenAccept";
            System.out.println(s);
        });
        cf3.get();
    }

    /**
     * 异步回调 有返回值
     *
     * @throws Exception
     */
    public static void demo2() throws Exception {
        // 创建异步返回任务
        CompletableFuture<String> cf = CompletableFuture.supplyAsync(() -> {
            return "hello";
        });
        //创建带返回值异步任务 cf2,该任务的需要cf的结果作为异步任务的参数
        CompletableFuture<String> cf2 = cf.thenApply(result -> {
            String s = result + " thenApply";
            return s;
        });
        System.out.println(cf2.get());
        CompletableFuture<String> cf3 = cf.thenApplyAsync(result -> {
            return result + " thenApplyAsync";
        });
        System.out.println(cf3.get());
    }

    /**
     * 异常回调
     *
     * @throws Exception
     */
    public static void demo3() throws Exception {
        // 创建异步返回任务
        CompletableFuture<Integer> cf = CompletableFuture.supplyAsync(() -> {
            Integer[] integers = new Integer[3];
            return integers[5];
        });
        //cf 发生异常后执行该方法,返回cf2结果
        // 如果没有发生异常不执行,并且返回cf的结果值
        CompletableFuture<Integer> cf2 = cf.exceptionally(e -> {
            System.out.println("cf exception " + e.getMessage());
            return 3;
        });
        System.out.println(cf2.get());
    }

    /**
     * 当某个任务执行完成后回调的方法,没有返回值
     *
     * @throws Exception
     */
    public static void demo4() throws Exception {
        // 创建异步返回任务
        CompletableFuture<String> cf = CompletableFuture.supplyAsync(() -> {
            return "hello";
        });
        // cf执行完成后会将执行结果与执行异常传染源回调方法 cf2
        CompletableFuture<String> cf2 = cf.whenComplete((a, e) -> {
            System.out.println("a:" + a);
            System.out.println("b:" + e.getMessage());
        });
        System.out.println(cf2.get());
    }

    /**
     * 当某个任务执行完成后回调的方法,有返回值
     *
     * @throws Exception
     */
    public static void demo5() throws Exception {
        // 创建异步返回任务
        CompletableFuture<String> cf = CompletableFuture.supplyAsync(() -> {
            return "hello";
        });
        // cf执行完成后会将执行结果与执行异常传染源回调方法 cf2
        // 参数 a 是cf的返回值,参数 e 是cf的异常
        CompletableFuture<String> cf2 = cf.handle((a, e) -> {
            System.out.println("a:" + a);
            System.out.println("b:" + e.getMessage());
            return " handle";
        });
        System.out.println(cf2.get());
    }

    /**
     * allOf / anyOf
     * 多个任务执行完成后才会执行
     *
     * @throws Exception
     */
    public static void demo6() throws Exception {
        // 创建异步返回任务
        CompletableFuture<String> cf = CompletableFuture.supplyAsync(() -> {
            return "hello";
        });

        // 创建异步返回任务
        CompletableFuture<String> cf2 = CompletableFuture.supplyAsync(() -> {
            return "word";
        });
        // allOf 所有任务执行完成后才会执行cf3.如果有一个任务异常中止,则cf3会抛出异常。如果全部正常执行,cf3会返回null
        CompletableFuture<Void> cf3 = CompletableFuture.allOf(cf, cf2).thenApply(result -> {
            return result;
        });
        System.out.println("cf3 " + cf3.get());

        //anyOf只要有一个任务执行完成,无论是正常执行还是执行异常,cf4的result都是已经执行完成任务的的结果
        CompletableFuture<Object> cf4 = CompletableFuture.anyOf(cf, cf2).thenApply(result -> {
            return result;
        });
        System.out.println("cf4:" + cf4.get());
    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值