首先,我们这里有三个方法,第一个方法执行700000000纳秒,第二个方法执行500000000纳秒,第三个方法执行100000000纳秒
@SneakyThrows
private String selectData1() {
TimeUnit.NANOSECONDS.sleep(700000000);
return "value1";
}
@SneakyThrows
private String selectData2() {
TimeUnit.NANOSECONDS.sleep(500000000);
return "value2";
}
@SneakyThrows
private String selectData3() {
TimeUnit.NANOSECONDS.sleep(100000000);
return "value3";
}
然后,我们通过简单的代码执行串行操作,大约是上面三个方法加起来的耗时
@GetMapping("/test1")
public Map<String, Object> test1() {
long start = System.nanoTime();
Map<String, Object> result = new ConcurrentHashMap<>();
result.put("key1", selectData1());
result.put("key2", selectData2());
result.put("key3", selectData3());
long end = System.nanoTime();
System.out.printf("test1耗时:%d纳秒\n", (end - start));
return result;
}
执行结果:test1耗时:1318577500纳秒
最后,我们通过java8来实现并行操作,耗时大约是这三个方法里面耗时最少的
@GetMapping("/test2")
public Map<String, Object> test2() {
long start = System.nanoTime();
Map<String, Object> result = new ConcurrentHashMap<>();
CompletableFuture.allOf(
CompletableFuture.runAsync(() -> {
result.put("key1", selectData1());
}, ForkJoinPool.commonPool()),
CompletableFuture.runAsync(() -> {
result.put("key2", selectData2());
}, ForkJoinPool.commonPool()),
CompletableFuture.runAsync(() -> {
result.put("key3", selectData3());
}, ForkJoinPool.commonPool())
).join();
long end = System.nanoTime();
System.out.printf("test2耗时: %d纳秒\n", (end - start));
return result;
}
执行结果:test2耗时: 709402400纳秒
CompletableFuture类
通过上面的类继承关系图可以知道CompletableFuture实现了Future接口和CompletionStage接口。因此CompletableFuture是对Future的功能增强包含了Future的功能。从继承的另一个CompletionStage的名称来看完成阶段性的接口。