[TOC]

多线程(CompletableFuture)异步工具

一、简单示例

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
@Test
public void run() throws ExecutionException, InterruptedException {
TimeUtil timeUtil = new TimeUtil();
timeUtil.begin();
CompletableFuture<String> helleFuture = CompletableFuture.supplyAsync(FutureTest::hello);
CompletableFuture<String> worldFuture = CompletableFuture.supplyAsync(FutureTest::world);
CompletableFuture.allOf(helleFuture,worldFuture).join();
System.out.println(helleFuture.get() + " " +worldFuture.get());
long time = timeUtil.getTime();
System.out.println(time);
}




public static String hello(){
try {
Thread.sleep(1000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "hello";
}

public static String world(){
try {
Thread.sleep(2000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "world";
}

二、