CompletableFuture异步编排

CompletableFuture异步编排
CompletableFuture提供了四个静态方法创建异步任务:

CompletableFuture.runAsync(Runnable runnable);

CompletableFuture.runAsync(Runnable runnable,Executor executor);

CompletableFuture.supplyAsync(Supplier supplier);

CompletableFuture.supplyAsync(Supplier supplier,Executor executor);
其中runXXX没有返回结果,supplyXXX可以获取返回结果;

都可以传入自定义的线程池,否则使用默认的线程池;

1)、whenComplete可以处理正常和异常的计算结果,exceptionally处理异常情况。
whenComplete获取上任务的结果:

public static void main(String[] args) {
	System.out.println("-----main start--------"+Thread.currentThread().getId());
	CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
		int a = 10 / 2;
		System.out.println("当前线程"+Thread.currentThread().getId()+"------当前结果" + a);
		return a;
	}).whenComplete((result,exception)->{
		System.out.println("异步任务完成了,结果:"+result);
		System.out.println("异步任务异常:"+exception);
	});
}

// 执行结果:
-----main start--------1
当前线程12------当前结果5
异步任务完成了,结果:5
异步任务异常:null
whenComplete获取上任务抛出的异常信息:

public static void main(String[] args) {
	System.out.println("-----main start--------"+Thread.currentThread().getId());
	CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
		int a = 10 / 0;
		System.out.println("当前线程"+Thread.currentThread().getId()+"------当前结果" + a);
		return a;
	}).whenComplete((result,exception)->{
		System.out.println("异步任务完成了,结果:"+result);
		System.out.println("异步任务异常:"+exception);
	});
}

// 执行结果:
-----main start--------1
异步任务完成了,结果:null
异步任务异常:java.util.concurrent.CompletionException: java.lang.ArithmeticException: / by zero
exceptionally捕获异常信息,返回默认值

public static void main(String[] args) throws Exception {
	System.out.println("-----main start--------"+Thread.currentThread().getId());
	CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
		int a = 10 / 0;
		System.out.println("当前线程"+Thread.currentThread().getId()+"------当前结果" + a);
		return a;
	}).whenComplete((result,exception)->{
		System.out.println("异步任务完成了,结果:"+result);
		System.out.println("异步任务异常:"+exception);
	}).exceptionally((exception)->{
		System.out.println("捕获异步任务异常:"+exception);
		return 10;
	});
	System.out.println("任务结果:"+future.get());
}

// 执行结果:
-----main start--------1
异步任务完成了,结果:null
异步任务异常:java.util.concurrent.CompletionException: java.lang.ArithmeticException: / by zero
捕获异步任务异常:java.util.concurrent.CompletionException: java.lang.ArithmeticException: / by zero
任务结果:10
exceptionally可以捕获到whenComplete的异常

public static void main(String[] args) throws Exception {
	System.out.println("-----main start--------"+Thread.currentThread().getId());
	CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
		int a = 10 / 2;
		System.out.println("当前线程"+Thread.currentThread().getId()+"------当前结果" + a);
		return a;
	}).whenComplete((result,exception)->{
		System.out.println("异步任务完成了,结果:"+result);
		System.out.println("异步任务异常:"+exception);
		throw new RuntimeException("whenComplete抛出异常");
	}).exceptionally((exception)->{
		System.out.println("捕获异步任务异常:"+exception);
		return 10;
	});
	System.out.println("任务结果:"+future.get());
}

// 执行结果:
-----main start--------1
当前线程12------当前结果5
异步任务完成了,结果:5
异步任务异常:null
捕获异步任务异常:java.util.concurrent.CompletionException: java.lang.RuntimeException: whenComplete抛出异常
任务结果:10
exceptionally抛出异常,任务结束

public static void main(String[] args) throws Exception {
	System.out.println("-----main start--------"+Thread.currentThread().getId());
	CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
		int a = 10 / 2;
		System.out.println("当前线程"+Thread.currentThread().getId()+"------当前结果" + a);
		return a;
	}).whenComplete((result,exception)->{
		System.out.println("异步任务完成了,结果:"+result);
		System.out.println("异步任务异常:"+exception);
		throw new RuntimeException("whenComplete抛出异常");
	}).exceptionally((exception)->{
		System.out.println("捕获异步任务异常:"+exception);
		throw new RuntimeException("任务执行失败");
	});
	System.out.println("任务结果:"+future.get());
}

// 执行结果:
-----main start--------1
当前线程12------当前结果5
异步任务完成了,结果:5
异步任务异常:null
捕获异步任务异常:java.util.concurrent.CompletionException: java.lang.RuntimeException: whenComplete抛出异常
Exception in thread “main” java.util.concurrent.ExecutionException: java.lang.RuntimeException: 任务执行失败
whenComplete 和 whenCompleteAsync 区别:

whenComplete:使用当前任务的线程继续执行;
whenCompleteAsync:把whenCompleteAsync任务继续提交给线程池来进行执行;
whenComplete:可以获取异常信息,但不能处理异常;
exceptionally:可以获取异常信息,进行异常处理;
2)、handle方法执行完成后的处理,与complete一样,可处理异常,也可返回默认值
handle捕获异常,返回默认值

public static void main(String[] args) throws Exception {
	System.out.println("-----main start--------"+Thread.currentThread().getId());
	CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
		int a = 10 / 0;
		System.out.println("当前线程"+Thread.currentThread().getId()+"------当前结果" + a);
		return a;
	}).handle((result,exception)->{
		System.out.println("异步任务完成了,结果:"+result);
		System.out.println("异步任务异常:"+exception);
		return 20;
	});
	System.out.println("任务结果:"+future.get());
}

//执行结果:
-----main start--------1
异步任务完成了,结果:null
异步任务异常:java.util.concurrent.CompletionException: java.lang.ArithmeticException: / by zero
任务结果:20
handle抛出异常,任务结束

public static void main(String[] args) throws Exception {
	System.out.println("-----main start--------"+Thread.currentThread().getId());
	CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
		int a = 10 / 0;
		System.out.println("当前线程"+Thread.currentThread().getId()+"------当前结果" + a);
		return a;
	}).handle((result,exception)->{
		System.out.println("异步任务完成了,结果:"+result);
		System.out.println("异步任务异常:"+exception);
		throw new RuntimeException("handle抛出异常");
	});
	System.out.println("任务结果:"+future.get());
}

//执行结果:
-----main start--------1
异步任务完成了,结果:null
异步任务异常:java.util.concurrent.CompletionException: java.lang.ArithmeticException: / by zero
Exception in thread “main” java.util.concurrent.ExecutionException: java.lang.RuntimeException: handle抛出异常
3)、线程串行化方法
线程串行化thenRun():不能获取到上一步任务的执行结果,不能捕获上一步异常,上一步异常任务结束

public static void main(String[] args) throws Exception {
	System.out.println("-----main start--------"+Thread.currentThread().getId());
	CompletableFuture.supplyAsync(() -> {
		int a = 10 / 0;
		System.out.println("当前线程"+Thread.currentThread().getId()+"------当前结果" + a);
		return a;
	}).thenRun(()->{
		System.out.println("任务2启动了");
	});
	System.out.println("任务结果:");
}

// 执行结果:
-----main start--------1
任务结果:
线程串行化thenRun():不能获取到上一步任务的执行结果,无返回值

public static void main(String[] args)  {
	System.out.println("-----main start--------"+Thread.currentThread().getId());
	CompletableFuture.supplyAsync(() -> {
		int a = 10 / 2;
		System.out.println("当前线程"+Thread.currentThread().getId()+"------当前结果" + a);
		return a;
	}).thenRun(()->{
		System.out.println("任务2启动了");
	});
	System.out.println("任务结果:");
}

// 执行结果:
-----main start--------1
当前线程12------当前结果5
任务2启动了
任务结果:
线程串行化thenRun():不能获取到上一步任务的执行结果,无返回值,发生异常时不会抛出异常

public static void main(String[] args)  {
	System.out.println("-----main start--------"+Thread.currentThread().getId());
	CompletableFuture.supplyAsync(() -> {
		int a = 10 / 2;
		System.out.println("当前线程"+Thread.currentThread().getId()+"------当前结果" + a);
		return a;
	}).thenRun(()->{
		System.out.println("任务2启动了");
		throw new RuntimeException("任务2失败了");
	});
	System.out.println("任务结果:");
}

// 执行结果:
-----main start--------1
当前线程12------当前结果5
任务2启动了
任务结果:
线程串行化thenAccept():可以获取上一步结果,异常与thenRun()方法一致

public static void main(String[] args)  {
	System.out.println("-----main start--------"+Thread.currentThread().getId());
	CompletableFuture.supplyAsync(() -> {
		int a = 10 / 2;
		System.out.println("当前线程"+Thread.currentThread().getId()+"------当前结果" + a);
		return a;
	}).thenAccept((result)->{
		System.out.println("任务1执行结果"+result);
		System.out.println("任务2启动了");
		throw new RuntimeException("任务2失败了");
	});
	System.out.println("任务结果:");
}

//执行结果:
-----main start--------1
当前线程12------当前结果5
任务1执行结果5
任务2启动了
任务结果:
线程串行化thenAccept():可以获取上一步结果,异常与thenRun()方法一致

public static void main(String[] args)  {
	System.out.println("-----main start--------"+Thread.currentThread().getId());
	CompletableFuture.supplyAsync(() -> {
		int a = 10 / 2;
		System.out.println("当前线程"+Thread.currentThread().getId()+"------当前结果" + a);
		return a;
	}).thenAccept((result)->{
		System.out.println("任务1执行结果"+result);
		System.out.println("任务2启动了");
		throw new RuntimeException("任务2失败了");
	});
	System.out.println("任务结果:");
}

//执行结果:
-----main start--------1
当前线程12------当前结果5
任务1执行结果5
任务2启动了
任务结果:
线程串行化thenApply():可以获取上一步结果,有返回值

public static void main(String[] args) {
System.out.println(“-----main start--------”+Thread.currentThread().getId());
CompletableFuture future = CompletableFuture.supplyAsync(() -> {
int a = 10 / 2;
System.out.println(“当前线程” + Thread.currentThread().getId() + “------当前结果” + a);
return a;
}).thenApply((result) -> {
System.out.println(“任务1执行结果” + result);
System.out.println(“任务2启动了”);
return 100;
});
Integer result=null;
try {
result = future.get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
System.out.println(“任务结果:”+result);
}
//执行结果:
-----main start--------1
当前线程12------当前结果5
任务1执行结果5
任务2启动了
任务结果:100
线程串行化thenApply():可以获取上一步结果,有返回值,可抛出异常,上一步发生异常任务结束

public static void main(String[] args)  {
	System.out.println("-----main start--------"+Thread.currentThread().getId());
	CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
		int a = 10 / 2;
		System.out.println("当前线程" + Thread.currentThread().getId() + "------当前结果" + a);
		return a;
	}).thenApply((result) -> {
		System.out.println("任务1执行结果" + result);
		System.out.println("任务2启动了");
		throw new RuntimeException("任务2发生异常了");
	});
	Integer result=null;
	try {
		result = future.get();
	} catch (InterruptedException e) {
		e.printStackTrace();
	} catch (ExecutionException e) {
		e.printStackTrace();
	}
	System.out.println("任务结果:"+result);
}

//执行结果:
-----main start--------1
当前线程12------当前结果5
任务1执行结果5
任务2启动了
任务结果:null
java.util.concurrent.ExecutionException: java.lang.RuntimeException: 任务2发生异常了
thenApply 、thenAccept、thenRun 区别:

thenApply:当一个线程依赖另一个线程时,获取上一个任务返回的结果,并返回当前任务的返回值;
thenAccept:消费处理结果。接收任务处理的结果,并消息处理,无返回结果;
thenRun:只要上面的任务执行完成,就开始执行thenRun,只是处理完任务后,执行thenRun的后续操作;
4)、两任务组合,都要完成
runAfterBoth()无返回结果:任务1和任务2执行完成,执行当前任务;任务1和任务2任一抛出异常,任务3不执行;任一任务不会抛出异常;

public static void main(String[] args)  {
	System.out.println("-----main start--------"+Thread.currentThread().getId());
	CompletableFuture<Integer> future1 = CompletableFuture.supplyAsync(() -> {
		int a = 10 / 2;
		System.out.println("当前线程" + Thread.currentThread().getId() + "------任务一结果:" + a);
		return a;
	});

	CompletableFuture<Integer> future2 = CompletableFuture.supplyAsync(() -> {
		int a = 10 / 0;
		System.out.println("当前线程" + Thread.currentThread().getId() + "------任务二结果:" + a);
		return a;
	});

	future1.runAfterBoth(future2,()->{
		int a=1/0;
		System.out.println("任务三开始了"+a);
	});

	System.out.println("任务结果:");
}

//执行结果:
-----main start--------1
当前线程12------任务一结果:5
任务结果:
runAfterBoth()无返回结果,可得到任务1和任务2结果:任务1和任务2任一抛出异常,任务3不执行;任一任务不会抛出异常;

public static void main(String[] args)  {
	System.out.println("-----main start--------"+Thread.currentThread().getId());
	CompletableFuture<Integer> future1 = CompletableFuture.supplyAsync(() -> {
		int a = 10 / 2;
		System.out.println("当前线程" + Thread.currentThread().getId() + "------任务一结果:" + a);
		return a;
	});

	CompletableFuture<Integer> future2 = CompletableFuture.supplyAsync(() -> {
		int a = 10 / 2;
		System.out.println("当前线程" + Thread.currentThread().getId() + "------任务二结果:" + a);
		return a;
	});

	future1.thenAcceptBothAsync(future2,(f1,f2)->{
		System.out.println("任务一结果:"+f1+"---任务二结果:"+f2);
		int a=1/0;
		System.out.println("任务三开始了"+a);
	});

	System.out.println("任务结果:");
}

-----main start--------1
当前线程12------任务一结果:5
当前线程12------任务二结果:5
任务结果:
任务一结果:5—任务二结果:5
runAfterBoth()有返回结果,可得到任务1和任务2结果:任务1和任务2任一抛出异常,任务3不执行;可捕获任务3的异常;

public static void main(String[] args)  {
	System.out.println("-----main start--------"+Thread.currentThread().getId());
	CompletableFuture<Integer> future1 = CompletableFuture.supplyAsync(() -> {
		int a = 10 / 2;
		System.out.println("当前线程" + Thread.currentThread().getId() + "------任务一结果:" + a);
		return a;
	});

	CompletableFuture<Integer> future2 = CompletableFuture.supplyAsync(() -> {
		int a = 10 / 2;
		System.out.println("当前线程" + Thread.currentThread().getId() + "------任务二结果:" + a);
		return a;
	});

	CompletableFuture<Integer> future = future1.thenCombineAsync(future2, (f1, f2) -> {
		System.out.println("任务一结果:" + f1 + "---任务二结果:" + f2);
		int a = 1 / 0;
		System.out.println("任务三开始了" + a);
		return a;
	});

	Integer integer = null;
	try {
		integer = future.get();
	} catch (InterruptedException e) {
		e.printStackTrace();
	} catch (ExecutionException e) {
		e.printStackTrace();
	}
	System.out.println("任务结果:"+integer);
}

-----main start--------1
当前线程12------任务一结果:5
当前线程12------任务二结果:5
任务一结果:5—任务二结果:5
任务结果:null
java.util.concurrent.ExecutionException: java.lang.ArithmeticException: / by zero
thenCombine 、thenAcceptBoth、runAfterBoth 区别:

thenCombine:组合两个future,获取两个future的返回结果,并返回当前任务的返回值;
thenAcceptBoth:组合两个future,获取两个future任务的返回结果,然后处理任务,没有返回值;
runAfterBoth:组合两个future,不需要获取future的结果,只需要两个future处理完任务后,处理该任务;
5)、两任务组合,一个完成
applyToEither 、acceptEither、runAfterEither 区别:

applyToEither:两个任务有一个执行完成,获取它的返回值,处理任务并有新的返回值;
acceptEither:两个任务有一个执行完成,获取它的返回值,处理任务,没有新的返回值;
runAfterEither:两个任务有一个执行完成,不需要获取future的结果,处理任务,也没有返回值;
6)、多任务组合
allOf 、anyOf 区别:

allOf:等待所有任务完成
anyOf:只要有一个任务完成

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值