異步操作之 CompletableFuture

CompletableFuture 也可以異步執行方法

1、無返回結果的示例

final CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
   log.info("返回 Void 的 CompletableFuture 操作示例");
}).exceptionally(throwable -> {
   log.error(throwable.getMessage());
   return null;
});

future.get();
RedisClientTest.log.info("------- 結束 ---------");

2、返回基本類型的示例

final CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
   return "返回 String 的 CompletableFuture 操作示例";
}).exceptionally(throwable -> {
   log.info(throwable.getMessage());
   return "-1";
});
final String result = future.get();
log.info("result:" + result);

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章