Java异步处理(1.8之后)

本文详细解析了JDK1.8如何通过CompletableFuture实现异步操作,包括创建异步操作的方法、异步操作完成时的回调、串行化方法等,并对比了runAsync与supplyAsync、whenComplete与whenCompleteAsync的功能与使用场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

jdk1.8才算是真正支持了异步操作,利用jdk1.8中提供的lambada表达式,借助CompletableFuture可以实现异步的操作,同时lambada又大大简化了代码量。

CompletableFuture的使用详解:

a.创建异步操作的方法
 	public static CompletableFuture<Void> runAsync(Runnable runnable)
    public static CompletableFuture<Void> runAsync(Runnable runnable, Executor executor)
    public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier)
    public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier, Executor executor)

Executor方法既可以制定也可以不指定,不指定的话ForkJoinPool.commonPool() 作为它的线程池执行异步代码。
区别:runAsync方法不支持返回值,supplyAsync可以支持返回值。

b.在异步操作完成时的回调方法
     public CompletableFuture<T> whenComplete(BiConsumer<? super T,? super Throwable> action)
     public CompletableFuture<T> whenCompleteAsync(BiConsumer<? super T,? super Throwable> action)
     public CompletableFuture<T> whenCompleteAsync(BiConsumer<? super T,? super Throwable> action, Executor executor)
     public CompletableFuture<T> exceptionally(Function<Throwable,? extends T> fn)
whenComplete方法和whenCompleteAsync方法是当异步操作执行完之后执行操作的方法,他们两个的区别是做前者用之前的线程进行,后者则是使用线程池来执行
exceptionally则是出现异常的时候执行操作的方法
c.串行化方法thenApply,前置任务出现异常则无法执行
```
    public <U> CompletableFuture<U> thenApply(Function<? super T,? extends U> fn)
    public <U> CompletableFuture<U> thenApplyAsync(Function<? super T,? extends U> fn)
    public <U> CompletableFuture<U> thenApplyAsync(Function<? super T,? extends U> fn, Executor executor)
d.串行化方法handle,前置任务出现异常也可以执行
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值