1、测试异步调用:
static void testCompletableFuture1() throws ExecutionException, InterruptedException {
// 1、无返回值的异步任务。异步线程执行Runnable
CompletableFuture.runAsync(() -> System.out.println("only you"));
// 2、有返回值的异步任务。执行Supplier函数并返回结果
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> "3个时辰内必须找人解毒,不过老夫也可以帮忙哦");
System.out.println("supplyAsync, result: " + future.get()); // 阻塞获取结果
}
打印:
2、链式调用:
static void testCompletableFuture2() throws ExecutionException, InterruptedException {
System.out.println("main thread, id: " + Thread.currentThread().getId());
// 链式操作
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
System.out.println("supplyAsync thread: " + Thread.currentThread().getId());
return "我行我素";
});
// 结果转换
future = future.thenApply(s -> {
System.out.println("thenApply thread: " + Thread.currentThread().getId());
return s + " !!!";
});
// 结果消费
CompletableFuture<Void> future2 = future.thenAccept(s -> {
System.out.println("thenAccept thread: " + Thread.currentThread().getId());
System.out.println(s);// 输出结果
});
}
打印:
3、依赖其他Future任务
// thenCompose()串联多个异步任务,前一个任务结果为后一个任务的输入
static void testCompletableFuture3() throws ExecutionException, InterruptedException {
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> "haiyangxuanfeng");
future = future.thenCompose(s -> CompletableFuture.supplyAsync(s::toUpperCase));
future.thenAccept(new Consumer<String>() {
@Override
public void accept(String s) {
System.out.println(s);
}
}).get();
}
打印: