一. 概述

在开发中, 经常碰到一写场景就是, 一些耗时的操作有时与业务主干关联性不大, 为了提高业务主干的响应速度, 我们会把这些耗时的任务异步处理. 本文介绍的异步工具类是java8自带的工具类-CompletableFuture, 详细api请查看官方的api, 本文主要介绍常用方法使用

二. 常用方法介绍

2.1 异步执行方法

public static void main(String[] args) throws Exception{
// 返回一个新的CompletableFuture,通过运行在 ForkJoinPool.commonPool()中的任务与通过调用给定的供应商获得的值 异步完成。
CompletableFuture supplyAsync = CompletableFuture.supplyAsync(() -> {
return helloWorld();
});
// 返回一个新的CompletableFuture,它在运行给定操作后由运行在 ForkJoinPool.commonPool()中的任务 异步完成。
CompletableFuture.runAsync(() -> helloWorld());
}
public static String helloWorld(){
return "helloWorld";
}
2.2 获取异步返回的结果
public static void main(String[] args) throws Exception{
// 返回一个新的CompletableFuture,通过运行在 ForkJoinPool.commonPool()中的任务与通过调用给定的供应商获得的值 异步完成。
CompletableFuture future = CompletableFuture.supplyAsync(() -> {
return helloWorld();
});
// 等待这个未来完成的必要,然后返回"helloWorld"。
String str1 = future.get();
// 如果已完成,则返回"helloWorld"(或抛出任何遇到的异常),否则返回"hi"。
String str2 = future.getNow("hi");
// 等待3秒, 执行完了就返回"helloWorld"
String str3 = future.get(3, TimeUnit.SECONDS);
}
public static String helloWorld(){
return "helloWorld";
}