CompletableFuture1
2024-10-19 00:21:20
public class CompletableFutureTest {
public static void main(String[] args) throws Exception { test5(); } /**
* whenCompleteAsync指的是异步执行传入的BiConsumer
* whenComplete 指的是同步执行传入的BiConsumer
*/
public static void test1() throws ExecutionException, InterruptedException {
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> "hello");
//future.whenCompleteAsync((v, r) -> {
future.whenComplete((v, r) -> {
System.out.println("=========");
try {
TimeUnit.SECONDS.sleep();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("====over=====");
});
System.out.println("^^^^^^^^^^");
System.out.println(future.get());
Thread.currentThread().join();
} /**
* 同样有异步和同步两种方法,thenApply没有异常处理
* @throws ExecutionException
* @throws InterruptedException
*/
public static void test2() throws ExecutionException, InterruptedException {
CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> "hello")
.thenApply((s) -> {
try {
System.out.println("==========");
TimeUnit.SECONDS.sleep();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("====over=====");
return s.length();
});
// .thenApplyAsync((s) -> {
// try {
// System.out.println("==========");
// TimeUnit.SECONDS.sleep(5);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// System.out.println("====over=====");
// return s.length();
// });
System.out.println("^^^^^^^^^^");
System.out.println(future.get());
Thread.currentThread().join();
} /**
* handleAsync 有异常处理
* @throws ExecutionException
* @throws InterruptedException
*/
public static void test3() throws ExecutionException, InterruptedException {
CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> "hello")
.handleAsync((v, t) -> {
return v.length();
});
System.out.println(future.get());
} /**
* thenAcceptAsync 直接将上一个的结果进行消费
* @throws ExecutionException
* @throws InterruptedException
*/
public static void test4() throws ExecutionException, InterruptedException {
CompletableFuture.supplyAsync(() -> "hello")
.thenAcceptAsync((x) -> {
System.out.println(x);
});
} /**
*执行完上一个future后再执行一个runnable
* @throws ExecutionException
* @throws InterruptedException
*/
public static void test5() throws ExecutionException, InterruptedException {
CompletableFuture.supplyAsync(() -> "hello")
.thenRunAsync(() -> {
System.out.println("====over===");
});
}
}
最新文章
- linux 环境下运行STS时 出现must be available in order to run STS
- HTTP TCP UDP Socket 关系的几个经典图
- hihoCoder#1039
- C# Use Pop3Client to read gmail
- Javascript基础系列之(六)循环语句(do while循环)
- IIS Handler and Module探索
- initrd.gz的解压和制作
- PL/SQL(二):变量
- TopCoder中插件的用法
- hunnu-11546--Sum of f(x)
- RH033读书笔记(3)-Lab 4 Browsing the Filesystem
- c3p0、dbcp、tomcat jdbc pool 连接池配置简介及常用数据库的driverClass和驱动包
- 11154 LRC才不会告诉你们的事情
- Android硬件编解码与软件编解码
- Python基础数据类型之字典
- UE4 C++与蓝图交互
- java自带dom工具使用实例
- Android项目刮刮奖详解扩展篇——开源刮刮奖View的制作
- Flink学习(二)Flink中的时间
- CF980E The Number Games