hooyantsing's Blog

29_异步回调

字数统计: 273阅读时长: 1 min
2020/08/28

29 异步回调

狂神说Java JUC并发编程最新版通俗易懂

详见 辅佐资料_Java CompletableFuture 使用详解 - 简书

CompletableFuture 类提供了两类异步操作:

  • runAsync 无返回值异步操作
  • supplyAsync 有返回值异步操作

    案例

两类异步操作。

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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
package future;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

/**
* Ajax 类似
*/
public class Demo1 {
public static void main(String[] args) throws ExecutionException, InterruptedException {
/**
* 没有返回值
*/
CompletableFuture<Void> cf1 = CompletableFuture.runAsync(
() -> {
try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "runAsync -> Void");
}
);

System.out.println("没有返回值异步调用");
cf1.get();

/**
* 有返回值
* 成功 / 失败回调
*/
CompletableFuture<Integer> cf2 = CompletableFuture.supplyAsync(
() -> {
System.out.println(Thread.currentThread().getName() + "supplyAsync -> Integer");
return 1024;
}
);

// 回调
// whenComplete t接收成功回调,u接收失败回调
// exceptionally e 接收失败回调
Future<Integer> future = cf2.whenComplete(
(t,u) -> {
System.out.println("T=> " + t);
System.out.println("U=> " + u);
}
).exceptionally(
(e) -> {
e.getMessage();
return 0;
}
);

System.out.println(future.get());
}
}

运行结果:

CATALOG
  1. 1. 29 异步回调
    1. 1.0.1. 案例