Java异步编程

1、创建completablefuture**
  CompletableFuture<String> completableFuture = new CompletableFuture<String>();
  String result = completableFuture.get();
2、使用runAsync进行异步计算

使用场景: 后台异步计算一个无返回值的接口

public static void test() throws ExecutionException, InterruptedException {
    CompletableFuture<Void> completableFuture1 = CompletableFuture.runAsync(() -> getRunTest());
    completableFuture1.get();
}
private static void getRunTest() {
    System.out.println("test");
}
3、使用supplyAsync进行异步计算

使用场景: 运行一个异步任务并且返回结果

public static SyncVo supplyAsync() throws ExecutionException, InterruptedException {
    CompletableFuture<SyncVo> completableFuture = CompletableFuture.supplyAsync(() -> getSupplyAsync(), AsyncUtil::execute);
    return completableFuture.get();
}
4、CompletableFuture 转换和运行

CompletableFuture.get()方法是阻塞的,会一直等到Future完成并且在完成后返回结果。可以使用 thenApply(), thenAccept() 和thenRun()方法附上一个回调给CompletableFuture。

thenApply() 可以使用 thenApply() 处理和改变CompletableFuture的结果

public static String thenApply() throws ExecutionException, InterruptedException {
    CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(() -> getTheSupply()).thenApply(o -> o + "test2");
    String result = completableFuture.get();
    System.out.println(result);
    return result;
}
//处理对象
public static SyncVo thenApply() throws ExecutionException, InterruptedException {
    CompletableFuture<SyncVo> completableFuture = CompletableFuture.supplyAsync(() -> getSupplyAsync()).thenApply(o-> getSyncVo(o));
    return completableFuture.get();
}

  转载请注明: Hi 高虎 Java异步编程

  目录