38 lines
1.2 KiB
Java
38 lines
1.2 KiB
Java
package bunny.async;
|
|
|
|
import java.util.concurrent.CompletableFuture;
|
|
|
|
public class CompletableFutureTest1 {
|
|
public static void main(String[] args) throws Exception {
|
|
CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
|
|
// 模拟一个耗时的计算任务
|
|
try {
|
|
Thread.sleep(1000);
|
|
} catch (InterruptedException e) {
|
|
System.out.println(e.getMessage());
|
|
}
|
|
return 42;
|
|
});
|
|
|
|
future.thenAccept(result -> {
|
|
System.out.println("任务结果1: " + result);
|
|
});
|
|
|
|
// 等待所有任务完成
|
|
CompletableFuture.allOf(future).join();
|
|
|
|
// 返回结果为void
|
|
future.thenAccept(result -> System.out.println("任务结果2: " + result));
|
|
|
|
// thenApply 的链式调用
|
|
CompletableFuture<String> thenApply = future.thenApply(result -> {
|
|
System.out.println("任务结果3: " + result);
|
|
return "返回内容";
|
|
}).thenApply(result -> {
|
|
System.out.println("继续调用,看下之前结果:" + result);
|
|
return "最后一次返回";
|
|
});
|
|
System.out.println(thenApply.get());
|
|
}
|
|
}
|