# 异步任务学习笔记

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

@SpringBootTest
class Demo3ApplicationTests {

@Test
void contextLoads() {
run();
}


private void run() {
CompletableFuture<Void> f1 = CompletableFuture.runAsync(() -> {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("第一个异步任务");
});

CompletableFuture<Void> f2 = CompletableFuture.runAsync(() -> {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("第二个异步任务");
});
CompletableFuture.allOf(f1, f2).join();

f2.whenComplete(((aVoid, throwable) -> {
System.out.println("void f2" + aVoid);
}));

f1.whenComplete(((aVoid, throwable) -> {
System.out.println("void f1" + aVoid);
}));
System.out.println("CompletableFuture Test runAsync");
}

}

# Consumer 用法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

class Foo {
private Integer first;

public Integer getFirst() {
return first;
}

public void setFirst(Integer first) {
this.first = first;
}
}
public static void main(String[] args) {
Foo f = new Foo();
Consumer<Foo> consumer_fun = foo->foo.setFirst(1);
consumer_fun.accept(f);
System.out.println(f.getFirst());
}