CompletableFuture 通用異步編程
1. 多線程異步執(zhí)行,帶有返回值方法,避免使用get獲取結(jié)果集會(huì)阻塞線程.
2. 具體執(zhí)行業(yè)務(wù)邏輯方法
() -> { System.out.println(Thread.currentThread().getName() + "------come in");
int result = ThreadLocalRandom.current().nextInt(10);
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("---計(jì)算完成等待一秒鐘輸出結(jié)果");
return result;
3. 正常執(zhí)行結(jié)束
if (e == null) {
System.out.println("輸出完成" + v);
}
4. 異常執(zhí)行結(jié)束
e.printStackTrace();
System.out.println("執(zhí)行異常");
return null;
5. CompletableFuture好處
public static void main(String[] args) {
ExecutorService executorService = Executors.newFixedThreadPool(3);
try {
CompletableFuture.supplyAsync(() -> {
System.out.println(Thread.currentThread().getName() + "------come in");
int result = ThreadLocalRandom.current().nextInt(10);
try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); }
System.out.println("---計(jì)算完成等待一秒鐘輸出結(jié)果");
return result;
},executorService).whenComplete((v, e) -> {//當(dāng)執(zhí)行結(jié)束
if (e == null) {System.out.println("輸出完成" + v);} }).exceptionally(e -> {e.printStackTrace();System.out.println("執(zhí)行異常");
return null;
});
System.out.println("主線程執(zhí)行其他任務(wù)");
//主線程不要立刻結(jié)束,否則CompletableFuture默認(rèn)使用的線程池會(huì)立刻關(guān)閉,暫停三秒鐘結(jié)束
try {
TimeUnit.SECONDS.sleep(3);
} catch (InterruptedException e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
executorService.shutdown();
}
}
簡化執(zhí)行任務(wù)閉并返回?cái)?shù)據(jù)
ExecutorService executorService = Executors.newFixedThreadPool(3);
//調(diào)用異步有返回值方法
CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(() -> {
System.out.println(Thread.currentThread().getName());
return "hello word";
},executorService);
System.out.println(completableFuture.get());
executorService.shutdown();

image.png