JUC-13-异步回调

JUC-13-异步回调

1. 简介

  1. Future

mark

  1. CompletableFuture< T >

mark

2. 实际使用

  1. 没有返回值的runAsync异步回调
1
2
3
4
5
6
7
8
9
10
11
12
13
// 1. 没有返回值的runAsync异步回调
CompletableFuture<Void> completableFuture = CompletableFuture.runAsync(()->{
try {
// 阻塞两秒,模拟ajax
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"runASync->void");
});

System.out.println("waiting");
completableFuture.get() ; // 阻塞获取执行结果
  1. 有返回值的异步回调
  • 分别有成功的回调和失败的回调
1
2
3
4
5
6
7
8
9
10
11
12
13
14
// 2. 有返回值的异步回调
// 分别有成功的回调和失败的回调
CompletableFuture<Integer> CF = CompletableFuture.supplyAsync(()->{
System.out.println();
return 1024; // 成功返回1024
});

System.out.println(CF.whenComplete((t, u) -> {
System.out.println("t=" + t); // 正常的返回结果
System.out.println("u=" + u); // 如果有错,返回错误的信息
}).exceptionally((e) -> {
System.out.println(e.getMessage());
return 233; // 失败返回233
}).get());

底层源码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
    public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier) {
return asyncSupplyStage(asyncPool, supplier);
}


static <U> CompletableFuture<U> asyncSupplyStage(Executor e,
Supplier<U> f) {
if (f == null) throw new NullPointerException();
CompletableFuture<U> d = new CompletableFuture<U>();
e.execute(new AsyncSupply<U>(d, f));
return d;
}


public CompletableFuture<T> whenComplete(
BiConsumer<? super T, ? super Throwable> action) {
return uniWhenCompleteStage(null, action);
}


@FunctionalInterface
public interface BiConsumer<T, U> {

/**
* Performs this operation on the given arguments.
*
* @param t the first input argument
* @param u the second input argument
*/
void accept(T t, U u);
}
打赏
  • 版权声明: 本博客所有文章除特别声明外,均采用 Apache License 2.0 许可协议。转载请注明出处!
  • © 2019-2022 Zhuuu
  • PV: UV:

请我喝杯咖啡吧~

支付宝
微信