很久以前多線程是這樣創(chuàng)建:
Thread t1 = new Thread();
Thread t2 = new Thread();
t1.start(); // 啟動新線程
t2.start(); // 啟動新線程
由于創(chuàng)建和銷毀線程是非常耗資源,因此改成線程建好后不銷毀,可以重用,用戶只需提供run方法的具體實現(xiàn):
public static void main(String[] args) throws Exception {
ExecutorService executor = Executors.newSingleThreadExecutor();
Future<String> stringFuture = executor.submit(new Callable<String>() {
@Override
public String call() throws Exception {
Thread.sleep(2000);
return "async thread";
}
});
Thread.sleep(1000);
System.out.println("main thread");
System.out.println(stringFuture.get());
}
但如果很多線程被創(chuàng)建,并且線程間有依賴,即按流程和條件執(zhí)行線程,實現(xiàn)起來就有點復雜,于是CompletableFuture橫空出世。一共有50各方法可供使用。
CompletableFuture.supplyAsync(),相當于創(chuàng)建了ExecutorService,同時也創(chuàng)建了Callable,然后提交到線程池中執(zhí)行。
CompletableFuture<String> futureA = CompletableFuture.supplyAsync(() -> "任務(wù)A");
CompletableFuture<String> futureB = CompletableFuture.supplyAsync(() -> "任務(wù)B");
CompletableFuture<String> futureC = futureB.thenApply(b -> {
System.out.println("執(zhí)行任務(wù)C.");
System.out.println("參數(shù):" + b);//參數(shù):任務(wù)B
return "a";
});
!!How to use CompletableFuture and Callable in Java
https://ducmanhphan.github.io/2020-02-10-How-to-use-CompletableFuture-Callable-in-Java/使用CompletableFuture優(yōu)化你的代碼執(zhí)行效率
https://www.cnblogs.com/fingerboy/p/9948736.htmlCompletableFuture 使用詳解
https://www.jianshu.com/p/6bac52527ca4使用CompletableFuture
https://www.liaoxuefeng.com/wiki/1252599548343744/1306581182447650https://github.com/eugenp/tutorials/blob/master/core-java-modules/core-java-concurrency-basic/src/test/java/com/baeldung/completablefuture/CompletableFutureLongRunningUnitTest.java