forked from Java2ArkTS/Java2ArkTS
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCompletableFutureExample.java
More file actions
130 lines (110 loc) · 3.16 KB
/
Copy pathCompletableFutureExample.java
File metadata and controls
130 lines (110 loc) · 3.16 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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
public class CompletableFutureExample {
/**
* 任务 1:洗水壶 -> 烧开水
*/
private String task1() {
System.out.println("T1: 1");
for(int i = 0; i < 1000; i++);
System.out.println("T1: 2");
for(int i = 0; i < 1000; i++);
return null;
}
/**
* 任务 2:洗茶壶 -> 洗茶杯 -> 拿茶叶
*/
private String task2() {
System.out.println("T2: 1");
for(int i = 0; i < 1000; i++);
System.out.println("T2: 2");
for(int i = 0; i < 1000; i++);
System.out.println("T2: 3");
for(int i = 0; i < 1000; i++);
return " 龙井 ";
}
/**
* 任务 3:任务 1 和任务 2 完成后执行:泡茶
*/
private String task3(String tea) {
System.out.println("T1: 1" + tea);
System.out.println("T1: 2");
return " 上茶:" + tea;
}
public static void main(String[] args) {
CompletableFutureExample example = new CompletableFutureExample();
Thread t1 = new Thread(() -> {
example.task1();
});
final String[] tea = new String[1];
Thread t2 = new Thread(() -> {
tea[0] = example.task2();
});
t1.start();
t2.start();
String result = example.task3(tea[0]);
//System.out.println(result);
}
/**
* 描述串行关系
*/
static class SerialRelation {
private static String task1() {
return "Hello World";
}
private static String task2(String s) {
return s + " QQ";
}
private static String task3(String s) {
return s.toUpperCase();
}
public static void main(String[] args) {
String result = task1();
result = task2(result);
result = task3(result);
//System.out.println(result);
}
}
/**
* 描述汇聚Or关系
*/
static class ConvergeRelation {
private static String task1() {
int t = getRandom(5, 10);
for(int i = 0; i < 1000; i++);
return String.valueOf(t);
}
private static String task2() {
int t = getRandom(5, 10);
for(int i = 0; i < 1000; i++);
return String.valueOf(t);
}
private static int getRandom(int i, int j) {
return (int) (Math.random() * (j - i)) + i;
}
public static void main(String[] args) {
String result1 = task1();
String result2 = task2();
String result = result1 != null ? result1 : result2;
//System.out.println(result);
}
}
/**
* 处理异常
*/
static class ExceptionHandler {
private static int task() {
try {
return 7 / 0;
} catch (ArithmeticException e) {
return 0;
}
}
private static int task2(int r) {
return r * 10;
}
public static void main(String[] args) {
int result = task();
result = task2(result);
//System.out.println(result);
}
}
}