public class SpringbootWebApplicationTests {
private final Logger logger = LoggerFactory.getLogger(SpringbootWebApplicationTests.class);
private static final ExecutorService threadPool = Executors.newFixedThreadPool(5);
@Test
public void testCompletableFuture() throws Exception {
CompletableFuture.runAsync(() -> {
logger.info("runAsync--无返回值");
});
CompletableFuture.runAsync(() -> {
logger.info("runAsync--无返回值--指定线程池");
}, threadPool);
CompletableFuture<Integer> supplyAsync1 = CompletableFuture.supplyAsync(() -> {
logger.info("supplyAsync--有返回值");
return 1;
});
CompletableFuture<Integer> supplyAsync2 = CompletableFuture.supplyAsync(() -> {
logger.info("supplyAsync--有返回值--指定线程池");
return 1;
}, threadPool);
CompletableFuture<String> thenApply1 = supplyAsync1.thenApply((result) -> {
logger.info("thenApply:supplyAsync1执行完毕后的回调,参数为supplyAsync1任务的返回值");
return "result:" + result;
});
CompletableFuture<String> thenApply2 = supplyAsync2.thenApplyAsync((result) -> {
logger.info("thenApplyAsync:supplyAsync2执行完毕后的回调,参数为supplyAsync2任务的返回值");
return "result:" + result;
});
CompletableFuture<String> thenApply3 = supplyAsync2.thenApplyAsync((result) -> {
logger.info("thenApplyAsync--指定线程池:supplyAsync2执行完毕后的回调,参数为supplyAsync2任务的返回值");
return "result:" + result;
}, threadPool);
CompletableFuture<Void> thenAccept = thenApply1.thenAccept((result) -> {
logger.info("thenAccept:thenApply1执行完毕后的回调,参数为thenApply1任务的返回值,没有返回值");
int i = 1 / 0;
});
CompletableFuture<Void> thenRun = thenApply2.thenRun(() -> {
logger.info("thenRun:thenApply2执行完毕后的回调,没有参数,也没有返回值");
});
thenAccept.exceptionally((exception) -> {
logger.info("exceptionally:任务异常后的回调,参数为异常信息");
logger.info("异常信息", exception);
return null;
});
thenApply3.whenComplete((result, exception) -> {
logger.info("{},{}", result, exception);
logger.info("whenComplete:任务异常后的回调,会将执行结果或者执行期间抛出的异常传递给回调方法,如果是正常执行则异常为null");
});
thenApply3.whenCompleteAsync((result, exception) -> {
logger.info("{},{}", result, exception);
logger.info("whenCompleteAsync:任务异常后的回调,会将执行结果或者执行期间抛出的异常传递给回调方法,如果是正常执行则异常为null");
});
thenApply3.whenCompleteAsync((result, exception) -> {
logger.info("{},{}", result, exception);
logger.info("whenCompleteAsync--指定线程池:任务异常后的回调,会将执行结果或者执行期间抛出的异常传递给回调方法,如果是正常执行则异常为null");
}, threadPool);
logger.info("supplyAsync获取返回值:" + supplyAsync1.get() + "--" + supplyAsync2.get());
logger.info("thenApply获取返回值:" + thenApply1.get() + "--" + thenApply2.get() + "--" + thenApply3.get());
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!