-
Notifications
You must be signed in to change notification settings - Fork 267
Expand file tree
/
Copy pathCompletableFutureDemo2.java
More file actions
65 lines (54 loc) · 1.96 KB
/
Copy pathCompletableFutureDemo2.java
File metadata and controls
65 lines (54 loc) · 1.96 KB
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
59
60
61
62
63
64
65
package com.javaedge.concurrency.furure.jdk;
import lombok.extern.slf4j.Slf4j;
import java.util.Random;
import java.util.concurrent.CompletableFuture;
/**
* @author JavaEdge
* @date 2021/4/15
*/
@Slf4j
public class CompletableFutureDemo2 {
public static void main(String[] args) throws Exception {
CompletableFuture<String> future1 = CompletableFuture
// 1
.supplyAsync(() -> "Hello World")
// 2
.thenApply(s -> s + " Java")
// 3
.thenApply(String::toUpperCase);
System.out.println(future1.join());
// CompletableFuture<Integer> future2 = CompletableFuture
// .supplyAsync(() -> (1 / 0))
// .thenApply(r -> r * 2);
// System.out.println(future2.join());
CompletableFuture<Integer> future3 = CompletableFuture
.supplyAsync(() -> 1 / 0)
.thenApply(r -> r * 2)
.exceptionally(e -> 0);
System.out.println(future3.join());
Random rand = new Random(47);
CompletableFuture<String> f1 =
CompletableFuture.supplyAsync(() -> {
int t = rand.nextInt(20);
try {
Thread.sleep(t);
} catch (InterruptedException e) {
e.printStackTrace();
}
return String.valueOf(t);
});
CompletableFuture<String> f2 =
CompletableFuture.supplyAsync(() -> {
int t = rand.nextInt();
try {
Thread.sleep(t);
} catch (InterruptedException e) {
e.printStackTrace();
}
return String.valueOf(t);
});
CompletableFuture<String> f3 =
f1.applyToEither(f2, s -> s);
System.out.println(f3.join());
}
}