CompletableFuture---1
1 /**
2 * 两个任务同时并发执行 并有结果值返回
3 * @throws Exception
4 */
5 public static void test1() throws Exception{
6 StopWatch stopWatch = new StopWatch();
7 stopWatch.start();
8 CompletableFuture<String> future1 = new CompletableFuture<>();
9 new Thread(new Runnable() {
10 @Override
11 public void run() {
12 try {
13 System.out.println("future1");
14 Thread.sleep(1500);
15 future1.complete("I LOVE YOU1");
16 }catch (Exception e){
17 System.out.println(e);
18 }
19 }
20 }).start();
21
22
23 CompletableFuture<String> future2 = new CompletableFuture<>();
24 new Thread(new Runnable() {
25 @Override
26 public void run() {
27 try {
28 System.out.println("future2");
29 Thread.sleep(2000);
30 future2.complete("I LOVE YOU2");
31 }catch (Exception e){
32 System.out.println(e);
33 }
34 }
35 }).start();
36
37 System.out.println(future1.get() + "---" + future2.get());
38 stopWatch.stop();
39 System.out.println("stopWatch.getTotalTimeMillis():" + stopWatch.getTotalTimeMillis());
40 }
返回结果如下图所示:
future1
future2
I LOVE YOU1---I LOVE YOU2
stopWatch.getTotalTimeMillis():2005
郭慕荣博客园