CompletableFuture的runAfterBothAsync
runAfterBothAsync:假設有兩個線程A和B,這兩個線程都是異步執行的,但是不确定A和B何時執行完畢,但是需要在A和B都執行完畢後運作線程C。
private void test() {
System.out.println("開始...");
CompletableFuture.supplyAsync(new Supplier<String>() {
@Override
public String get() {
try {
TimeUnit.SECONDS.sleep(3);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("傳回 zhang");
return "zhang";
}
}).runAfterBothAsync(CompletableFuture.supplyAsync(new Supplier<String>() {
@Override
public String get() {
try {
TimeUnit.SECONDS.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("傳回 phil");
return "phil";
}
}), new Runnable() {
@Override
public void run() {
System.out.println("開始 run");
}
});
}
代碼運作結果輸出:
07-02 14:06:59.016 23450-23450/zhangphil.test I/System.out: 開始...
07-02 14:07:02.020 23450-23493/zhangphil.test I/System.out: 傳回 zhang
07-02 14:07:04.021 23450-23494/zhangphil.test I/System.out: 傳回 phil
開始 run
線程傳回“zhang”和"phil"後, 開始運作線程Runnable裡面的線程體。注意傳回“zhang”和“phil”的線程是同時執行的。