Java8中并行操作的方法及示例分享
下文笔者讲述java8中并行操作的方法及示例分享,如下所示
并行操作的方法
借助 CompletableFuture 类中的方法
CompletableFuture.allOf(
CompletableFuture.runAsync(方法))
例:
定义三个方法
第一个方法执行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纳秒
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。


